简短的问题:我可以在 defineProperty 调用中使用对象作为值吗?目前我有一个类的所有实例共享同一个对象的问题。
小例子:
var Test = function () {
};
var p = Test.prototype;
Object.defineProperty(p, 'object', {
value: new TestObject(),
enumerable: true,
writeable: false
});
一个简单的测试用例:
var x = new Test();
var y = new Test();
y.object.test = 'Foobar';
console.log(x.object.test); // --> Foobar
目前我必须以这种方式解决这个问题:
var Test = function () {
this.initialize();
};
var p = Test.prototype;
p._object = null;
p.initialize = function () {
this._object = new TestObject();
};
Object.defineProperty(p, 'object', {
get: function () { return this._object; },
enumerable: true
});
是否有可能在没有额外属性的情况下获得解决方案?