我正在尝试在我的代码中使用javascript继承。以下是相同的jsfiddle。 http://jsfiddle.net/Fetsz/3/
var baseObject = Object.create(Object, {
// this works as an instance variable for derived objects
name: {
writable: true,
configurable: true,
enumerable: true,
value: null
},
// this should act as instance variable for derived objects
values: {
writable: true,
configurable: true,
enumerable: true,
value: []
},
displayAlert: {
value: function (){
alert("Alert from base object");
}
}
});
var derivedObj1 = Object.create(baseObject, {});
var derivedObj2 = Object.create(baseObject, {});
function displayValues (obj) {
alert("values for " + obj.name + "\n" + JSON.stringify(obj.values));
};
$(document).ready(function(){
derivedObj1.name = "Object 1";
derivedObj2.name = "Object 2";
derivedObj1.values.push("DO1 element");
derivedObj2.values.push("DO2 element");
derivedObj1.displayAlert();
// should display values added only for derivedObj1
displayValues(derivedObj1);
// should display values added only for derivedObj2
displayValues(derivedObj2);
});
我还检查了以下问题,这很好地解释了为什么我的代码不起作用。 Javascript Inheritance: Parent's array variable retains value
我需要在每个派生类中都有一个包含某些值的数组成员变量。我试图通过在基类中添加数组来实现相同的目标。正如上面提到的问题,为了实现相同的目的,我将不得不为每个派生类添加数组成员。有没有其他方法来实现这一点而不修改每个派生类?
答案 0 :(得分:2)
创建它们时,derivedObj1.values
和derivedObj2.values
都指向同一个数组对象。如果您首先使用derivedObj1.values = [];
重新分配每个,请按照与重新分配name
属性相同的方式,您的代码将按预期运行。
您可以创建一个向实例添加数组的values
方法,而不是将init
属性添加到原始baseObject:
var baseObject = Object.create(Object, {
// this works as an instance variable for derived objects
name: {
writable: true,
configurable: true,
enumerable: true,
value: null
},
// this should act as instance variable for derived objects
init: {
writable: true,
configurable: true,
enumerable: true,
value: function(){
this.values = [];
}
},
displayAlert: {
value: function (){
alert("Alert from base object");
}
}
});
var derivedObj1 = Object.create(baseObject, {});
derivedObj1.init();
var derivedObj2 = Object.create(baseObject, {});
derivedObj2.init();
答案 1 :(得分:1)
如果您不希望所有实例共享变量,则您的变量不能在原型上。您可以仅使用数组的属性定义创建第二个对象,并将其作为第二个参数传递给Object.create
:
var arrDef = {
values: {
writable: true,
configurable: true,
enumerable: true,
value: []
}
}
var derivedObj1 = Object.create(baseObject, arrDef);
var derivedObj2 = Object.create(baseObject, arrDef);