0

short question: Can i use objects as value inside of a defineProperty call? Currently i have the problem that all instances of a class share the same object.

Little example:

  var Test = function () {
  };

  var p = Test.prototype;

  Object.defineProperty(p, 'object', {
    value: new TestObject(),
    enumerable: true,
    writeable: false
  });

A simple test case:

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

  y.object.test = 'Foobar';

  console.log(x.object.test); // --> Foobar

At the moment i must solve this problem on this way:

  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
  });

It is possible to get a solution without a extra property?

Shutterfly
  • 199
  • 12

1 Answers1

0

Just move the defineproperty from Test prototype definition to Test definition, so a new TestObject instance is created in the constructor call:

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
    });
};

A simple test case

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

see the fiddle

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169