【发布时间】:2017-01-15 05:03:30
【问题描述】:
我只是在玩弄用 Javascript 子类化的想法。我喜欢假装扩展原生对象(如数组、字符串等)是个坏主意。不管这是多么真实,我完全不明白为什么。
话虽如此,让我们继续吧。
我想做的是扩展 Array(现在,extend 可能不适合我正在做的事情)
我想创建我的新类MyArray,并且我想在上面设置 2 个方法。 .add 和 .addMultiple。
所以我是这样实现的。
function MyArray(){
var arr = Object.create(Array.prototype);
return Array.apply(arr, arguments);
}
MyArray.prototype = Array.prototype;
MyArray.prototype.add = function(i){
this.push(i);
}
MyArray.prototype.addMultiple = function(a){
if(Array.isArray(a)){
for(var i=0;i<a.length;i++){
this.add(a[i]);
}
}
}
这可以正常工作,但如果我这样做了
console.log(Array.prototype.addMultiple );
console.log(Array.prototype.add);
我得到[Function] 和[Function]。
所以这意味着我的代码正在修改本机 Array 对象。我试图避免的事情。如何更改此代码以使这两个console.logs 将给我undefined 但我仍然能够使用本机Array.prototype 方法,例如.push?
TIA
【问题讨论】:
标签: javascript inheritance prototype extend