Why modifying `Array.prototype` doesn't work?
Please refer - 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'
of undefined
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();
What?
Semicolons are optional in javascript, so the code you wrote is equivalent to:
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:
为我工作得很好,只是添加了一个字符:
Array.prototype.method1 = function() {
console.log("method1 has been called");
};
[1,2,3,4].method1();
链接地址: http://www.djcxy.com/p/19044.html
上一篇: JavaScript中的“点函数”操作符