首页 > 解决方案 > 在 javascript 中向 Array.prototype 添加新方法

问题描述

我是 Javascript 语言的新手,最近我开始研究 js 原型,但对以下代码中的一些奇怪输出感到困惑:

Array.prototype.print = function() {
  console.log(this)
}

[1, 2, 3, 4].print();

谁能告诉我为什么它会返回

无法读取未定义的属性“打印”

如果我声明var array = [1, 2, 3, 4]then 调用 print 函数array.print(),它工作正常,所以我很困惑那有什么不同?

Array.prototype.print = function() {
  console.log(this)
}

var array = [1, 2, 3, 4]
array.print()

标签: javascript

解决方案


您可以只添加一个分号来分隔对该函数的访问。

您拥有的是函数表达式的属性访问器,它带有逗号运算符,返回4访问。ASI(自动分号插入)在这种情况下不起作用。

Array.prototype.print = function() {
  console.log(this)
}[1, 2, 3, 4] //.print();   // tries to get property 4 of the function
                            // and then tries to call a function from undefined

它需要在函数表达式的块语句后加分号。

Array.prototype.print = function() {
  console.log(this)
};

[1, 2, 3, 4].print();


推荐阅读