![](/img/trans.png)
[英]If [] is [] and Array.prototype is [] why doesn't ([] == 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.