今天上了一个新的SVG框架我做我试图子阵列的工作与节点工作......并在几个小时后,我用这个代码(我只在Safari浏览器进行测试)完成:这是一个棘手的解决方案子类数组?
customArray=function(){
// Do the thing
this.__proto__= Array.prototype;
// Add some prototypes to the main customArray
this.f1=function(){console.log(1)}; // f1 custom function
this.f2=function(){console.log(2)}; // f2 custom function
};
newCustomArray=new customArray();
newCustomArray.f3=function(){console.log(3)} // f3 function only for newCustomArray
console.log(newCustomArray instanceof Array); // true
console.log([] instanceof Array); // true
console.log("---------------------");
console.log(newCustomArray.f1); // function(){console.log(1)};
console.log(newCustomArray.f2); // function(){console.log(2)};
console.log(newCustomArray.f3); // function(){console.log(3)};
console.log([].f1); // undefined
console.log([].f2); // undefined
console.log([].f3); // undefined
console.log("---------------------");
console.log(newCustomArray.forEach); // Native function
console.log([].forEach); // Native function
对我来说是工作,但作为“系统”说原型并不是无处不在。
'.__ proto__'是非标准的,所以它取决于其环境需要支持。 – 2013-02-20 01:49:07
非常感谢很多 – microbians 2013-02-20 01:53:01
由于通过'new'创建的对象只是一个普通对象(即Object的实例),因此不能“子类化”Array,只有真实数组才具有特殊的自我调整长度属性。简单地将一个对象的[[Prototype]]设置为'Array.prototype'只会让你获得方法。 – RobG 2013-02-20 03:06:27