为什么修改`Array.prototype`不起作用?

gop*_*rao 3 javascript

请参考 - https://jsfiddle.net/53ranmn5/1

Array.prototype.method1 = function() {
console.log("method1 called");
}
[1,2,3,4].method1();
Run Code Online (Sandbox Code Playgroud)

我收到以下错误,

类型错误:无法读取性能'method1'undefined

为什么这样?我怎样才能解决这个问题?

Zir*_*rak 9

你错过了一个分号:

Array.prototype.method1 = function() {
    console.log("method1 called");
}; // <--- Hi there!
[1,2,3,4].method1();
Run Code Online (Sandbox Code Playgroud)

什么?

分号在javascript中是可选的,因此您编写的代码相当于:

Array.prototype.method1 = function() { ... }[1,2,3,4].method1();
// after evaluating the comma operator:
Array.prototype.method1 = function() { ... }[4].method1();
// naturally, functions don't have a fourth index
undefined.method1();
// Error :(
Run Code Online (Sandbox Code Playgroud)

你的分号要小心!

一些阅读材料: