我正在尝试在我的代码中使用 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继承:父数组变量保留值
我需要在每个派生类中都有一个包含某些值的数组成员变量。我试图通过在基类中添加数组来实现相同的目的。正如上面问题中提到的,为了达到同样的效果,我必须向每个派生类添加数组成员。有没有其他方法可以在不修改每个派生类的情况下实现这一点?