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

时间:2015-04-23 14:39:57

标签: javascript

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

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

我收到以下错误,

  

TypeError:无法读取'method1'

的属性undefined

为什么这样?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:9)

你错过了一个分号:

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

什么?

分号在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 :(

小心你的分号!

一些阅读材料:

答案 1 :(得分:0)

对我来说很好,只添加了一个字符:

Array.prototype.method1 = function() {
    console.log("method1 has been called");
};
[1,2,3,4].method1();