0

简短的问题:我可以在 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
  });

是否有可能在没有额外属性的情况下获得解决方案?

4

1 回答 1

0

只需将 defineproperty 从 Test 原型定义移动到 Test 定义,因此在构造函数调用中创建了一个新的 TestObject 实例:

var TestObject = function() { }

var Test = function () {
    if(this==window) throw "Test called as a function";
    Object.defineProperty(this, 'object', {
      value: new TestObject(),
      enumerable: true,
      writeable: false
    });
};

一个简单的测试用例

var x = new Test();
var y = new Test();

x.object.test = 'Foo';
y.object.test = 'Bar';

console.log(x.object.test, y.object.test); // Foo Bar

看小提琴

于 2014-12-07T13:24:19.503 回答