【问题标题】:Adds new method to Array.prototype in javascript [duplicate]在javascript中向Array.prototype添加新方法[重复]
【发布时间】:2018-08-09 02:03:48
【问题描述】:

我是 Javascript 语言的新手,最近我开始研究 js 原型,并被以下代码中的一些奇怪输出弄糊涂了:

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

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

谁能告诉我为什么会返回

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

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

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

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

【问题讨论】:

  • 您是否同时运行两个代码块?当我单独运行每个块时,它对我有用,这表明存在竞争条件。确保第一个函数在调用最后一行之前已经运行。

标签: javascript


【解决方案1】:

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

您所拥有的是带有逗号运算符的函数表达式的property accessor,它返回4 以进行访问。 ASI (automatic semicolon insertion) 在这种情况下不起作用。

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();

【讨论】:

  • 是的输出是正确的,一旦我在打印功能后添加分号就没有错误出现,非常感谢!
  • 但我发现它对 String.prototype 工作正常,即使在函数后不插入分号.....你知道吗?
  • 可以加代码吗?
  • String.prototype.print = function() { console.log(this) } 'chen'.print();这个没有抛出任何错误;
  • } 之后你没有[,这是一个起始属性访问器。
【解决方案2】:

如果你一次运行整个代码块,不能保证最后一行会在第一个块之后运行。

分别运行这两个块将突出显示这种差异,您将看到第二个块的正确输出。

先运行这个:

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

然后运行这个:

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

有几种方法可以让它们异步运行。一个简单的方法是将最后一行包装在 setTimeout 中(根据您的使用情况,这可能不合适)。

例如

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

setTimeout(()=> { 
    [1, 2, 3, 4].print();
}, 1000)

【讨论】:

  • 感谢您的解决方案,这是绝对正确的,js 强制这两个语句合二为一并同时运行它们有点奇怪
猜你喜欢
  • 2014-04-18
  • 1970-01-01
  • 2011-09-10
  • 1970-01-01
  • 2011-01-01
  • 2013-05-05
  • 1970-01-01
  • 2021-07-08
  • 1970-01-01
相关资源
最近更新 更多