通过将对象的原型方法设置为Array方法,该对象的行为类似于对象和数组之间的混合.下面是一个简单的例子:
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 …Run Code Online (Sandbox Code Playgroud)