1

我正在尝试在我的代码中使用 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继承:父数组变量保留值

我需要在每个派生类中都有一个包含某些值的数组成员变量。我试图通过在基类中添加数组来实现相同的目的。正如上面问题中提到的,为了达到同样的效果,我必须向每个派生类添加数组成员。有没有其他方法可以在不修改每个派生类的情况下实现这一点?

4

2 回答 2

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();
于 2012-12-27T13:59:21.497 回答
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);    
于 2012-12-27T14:06:57.367 回答