当我将一个结构与一个函数的原型相关联,然后用该函数实例化多个对象时,它们都共享同一个结构实例。我希望每个对象都有自己的结构实例,而不必在实例化对象时显式创建新实例;那可能吗?
这是我正在尝试做的一个简明示例:
function defineClass(constructor, instanceMembers) {
constructor.prototype.model = instanceMembers.model;
return constructor;
}
var visualObject = defineClass(function () { }, {
model: {
setPosition: function (x, y) {
this.x = x;
this.y = y;
}
}
});
var testA = new visualObject();
var testB = new visualObject();
testA.model.setPosition(10, 10);
console.log(testB.model.x); // outputs "1", but want it to be undefined
这不起作用,因为 testA.model 和 testB.model 都引用了同一个实体。
如果我在构建时克隆结构,那么它可以工作,但我真的希望避免这种克隆操作。这段代码有效但伤害了我:
function defineClass(instanceMembers) {
var constructor = function () {
// Create a copy of the model member in this object instance
this.model = $.extend(true, {}, this.model);
};
constructor.prototype.model = instanceMembers.model;
return constructor;
}
var visualObject = defineClass({
model: {
setPosition: function (x, y) {
this.x = x;
this.y = y;
}
}
});
var testA = new visualObject();
var testB = new visualObject();
testA.model.setPosition(10, 10);
console.log(testB.model.x); // is undefined, as expected
javascript 是否提供了一种无需实例化复制的方法?