【发布时间】:2017-06-29 03:34:16
【问题描述】:
通过将对象的原型方法设置为数组方法,对象的行为就像是对象和数组的混合体。下面是一个简单的例子:
function Foo() {}
Foo.prototype.push = Array.prototype.push;
Foo.prototype.forEach = Array.prototype.forEach;
var foo = new Foo();
foo.push('abc');
foo.length; // = 1 as expected. But wait, why isn't foo.length undefined? How/when did this property get attached to foo?
foo[1] = 'def';
foo.length; // still = 1. But foo={0:'abc',1:'def'}, Why not =2?
foo.forEach(function(item) {
console.log(item)
}); //shows only'abc' and not 'def'
foo.push('ghi');
foo.length; // = 2, and now foo = {0:'abc', 1:'ghi'}. So it overwrote the key=1, which means its accessing the same location, but the first approach did not change the length ( didn't become a part of the array ) why ?
foo.forEach(function(item) {
console.log(item)
}); //now shows 'abc' and 'ghi'
为什么会发生所有这些奇怪的行为,为什么模仿这样的数组不好?
【问题讨论】:
-
因为javascript中的数组仍然是它下面的对象,它模仿了我们从其他语言中知道的数组。就像您创建自己的复杂性并且难以维护一样。下一个查看您的代码的人会更加困惑。
标签: javascript arrays object ecmascript-6 prototype