Javascript for … in loop with Object.prototype and Array.prototype properties
我正在阅读MDN文档以更好地理解JavaScript。这是从那里摘录的
1 2 3 4 5 6 7 8 9 | Object.prototype.objCustom = function() {}; Array.prototype.arrCustom = function() {}; let iterable = [3, 5, 7]; iterable.foo = 'hello'; for (let i in iterable) { console.log(i); // logs 0, 1, 2,"foo","arrCustom","objCustom" } |
在最坏的情况下,我以为它会打印
更新:1)如何可视化从
这是因为
1 2 3 4 5 6 7 8 9 | Object.prototype.objCustom = function() {}; Array.prototype.arrCustom = function() {}; let iterable = [3, 5, 7]; iterable.foo = 'hello'; Object.keys(iterable).forEach(function(key) { console.log(key); // logs 0, 1, 2,"foo" }); |
然而,在
在数组上使用
1)"How can i visualize the prototype chain from iterable to Array all the way upto
Object . Like is there any iterable.getParent method or iterable.myparent property which points to parent on it."
可以使用
1 2 3 4 | var proto = Object.getPrototypeOf(myObj); do { console.log(proto); } while((proto = Object.getPrototypeOf(proto))); |
2)"why it does not print array functions such as
toString , sort they are also onArray.prototype ."
3)"Do i need to use
hasOwnProperty always when someone add something toArray.prototype property."
不要在数组上使用
您还应该知道,在使用
因为
1 2 3 4 5 6 7 8 9 10 11 | Object.prototype.objCustom = function() {}; Array.prototype.arrCustom = function() {}; let iterable = [3, 5, 7]; iterable.foo = 'hello'; for (let i in iterable) { if (iterable.hasOwnProperty(i)) { console.log(i); } } |
1 2 3 4 5 6 7 8 9 10 11 12 | Object.prototype.objCustom = function() {}; Array.prototype.arrCustom = function() {}; let iterable = [3, 5, 7]; iterable.foo = 'hello'; for (let i in iterable) { if (iterable.hasOwnProperty(i)) console.log('own', i); // logs 0, 1, 2,"foo" else console.log('not', i); // logs"arrCustom","objCustom" (inherited) } |