[英]Why modifying `Array.prototype` doesn't work?
Please refer - https://jsfiddle.net/53ranmn5/1 请参考 - https://jsfiddle.net/53ranmn5/1
Array.prototype.method1 = function() {
console.log("method1 called");
}
[1,2,3,4].method1();
I get the following error, 我收到以下错误,
TypeError: Cannot read property
'method1'
ofundefined
TypeError:无法读取undefined
属性'method1'
Why so? 为什么这样? How can I fix this? 我怎样才能解决这个问题?
You're missing a semicolon: 你错过了一个分号:
Array.prototype.method1 = function() {
console.log("method1 called");
}; // <--- Hi there!
[1,2,3,4].method1();
Semicolons are optional in javascript, so the code you wrote is equivalent to: 分号在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 :(
Be careful with your semicolons! 你的分号要小心!
Some reading material: 一些阅读材料:
Works fine for me, just added one character: 对我来说很好,只添加了一个字符:
Array.prototype.method1 = function() {
console.log("method1 has been called");
};
[1,2,3,4].method1();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.