今天我正在研究一个新的 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并不无处不在。