繁体   English   中英

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

[英]Why modifying `Array.prototype` doesn't work?

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

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

我收到以下错误,

TypeError:无法读取undefined属性'method1'

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

你错过了一个分号:

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 :(

你的分号要小心!

一些阅读材料:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM