0

I'm trying to create a property within a prototype so it will be available in all instances (can't put it in the constructor and would prefer to not create it via instance.propertyname = *; if at all possible. As an example the code below:

function A() {

}
A.prototype.constructor = A;

Object.defineProperty(A.prototype, 'B', {
    writable: true,
    enumerable: true,
    value: null
});

var a = new A();
a.B = 'test';
var b = new A();
var c = new A();
b.B = '2';

console.log(a,b,c);

Produces the output:

A {B: "test", B: null} A {B: "2", B: null} A {B: null}

How do I get it to instead produce:

A {B: "test"} A {B: "2"} A {B: null}
CoryG
  • 2,429
  • 3
  • 25
  • 60
  • 2
    it works as expected ,dont be fooled by chrome logs. you wont override B in A prototype by assigning a B to its instances ,these are not the same B. – mpm Feb 28 '13 at 02:27
  • Ah thanks, didn't realize it was a chrome glitch. – CoryG Feb 28 '13 at 02:41
  • Be aware that if the default value of `B` is an object and not a primitive, then it is shared across all instances. The only way I found to prevent that is to define properties to `this` inside the constructor. – Mistic Mar 23 '15 at 10:37

0 Answers0