我不确定使用OLOO继承链中的每个对象都是独立的对象属性的最佳方法.
检查此小提琴或考虑以下代码: http:///HB7LU/19413/
Parent = {
array: [],
add: function(element) {
this.array.push(element this.array.length.toString());
return this;
},
getAll: function() {
return this.array;
}
};
Child = Object.create(Parent, {
removeAllButOne: { value: function() {
this.array.splice(1);
return this;
}}
});
foo = Object.create(Parent);
foo.add('foo');
bar = Object.create(Child);
bar.add('bar');
在小提琴中,单击foo或bar文本将调用foo.add(…)或bar.add(…)函数,将一个元素添加到对象数组,从而导致一个额外的< p>.标签在输出中. 结果不是我想要的. foo和bar共享同一数组.但是很容易理解会发生什么,如果我们查询对象继承,我们会看到以下内容:

好的,那我该怎么办?我想到了两种选择:
选项1) http:///HB7LU/19419/
Parent = function() {
return {
array: [],
add: function(element) {
this.array.push(element this.array.length.toString());
return this;
},
getAll: function() {
return this.array;
}
};
};
Child = Object.create(Parent(), {
removeAllButOne: { value: function() {
this.array.splice(1);
return this;
}}
});
foo = Object.create(Parent());
foo.add('foo');
bar = Object.create(Child);
bar.add('bar');
这将创建一个新的Parent对象,每次创建Parent对象或从(新的)Parent对象“继承”子对象时,都会创建Parent对象的所有功能.虽然这解决了我遇到的问题,但始终为每个子类型对象重复创建相同的函数似乎是一个坏主意.
选项2) http:///HB7LU/19420/
Parent = Object.create({
add: function(element) {
this.array.push(element this.array.length.toString());
return this;
},
getAll: function() {
return this.array;
}
}, {
ctor: { value: function(someArgs) {
this.array = [];
// maybe use someArgs
return this;
}}
});
Child = Object.create(Parent, {
removeAllButOne: { value: function() {
this.array.splice(1);
return this;
}}
});
foo = Object.create(Parent).ctor();
foo.add('foo');
bar = Object.create(Child).ctor();
bar.add('bar');
这似乎也解决了问题,但避免了Parent对象及其功能的重新生成.那么这是走的路吗?如果我在继承链中有多个孩子也都有私有财产怎么办?
像这样吗
Child = Object.create(Parent, {
ctor: { value: function(someArgs) {
this.__proto__.ctor(someArgs);
this.otherPrivate = {};
// maybe use someArgs
return this;
}},
removeAllButOne: { value: function() {
this.array.splice(1);
return this;
}}
});
孩子会用自己的功能遮盖父ctor …但是在其ctor函数中,他们可以调用父ctor而不破坏功能.
意见和建议深表感谢,谢谢! 解决方法: 最简单的方法是使用构造函数,因此始终在实例上将数组创建为自己的属性
// define Parent
function Parent() {
this.array = []; // array will be an instance property
}
Parent.prototype = {}; // inherit all the goodies from Object.prototype
Object.assign(Parent.prototype, { // using `Object.assign` for shorthand
add: function (element) {
this.array.push(element this.array.length.toString());
return this;
},
getAll: function () {
return this.array;
}
});
// define Child
function Child() {
Parent.apply(this); // apply Parent constructor to the instance
}
Child.prototype = Object.create(Parent.prototype); // inherit Parent's prototype chain
Object.assign(Child.prototype, {
removeAllButOne: function () {
this.array.splice(1);
return this;
}
});
现在有
var a = new Child(),
b = new Child();
a.array === b.array; // false
您也可以使用ES 6的类来编写此代码,但这只是我上面编写的语法糖,将产生相同的结构. 来源:https://www./content-1-565651.html
|