0

My javascript class prototype constructor is called only once for all my instances, instead of once per instance. What is the right way to have a unique super instance linked to a sub class?

Using the code below I would expect the output, all uniqueId's unique:

Org {uniqueId: 4}
Org {uniqueId: 5}
Org {uniqueId: 6}
Sub {uniqueSubId: 1, uniqueId: 1}
Sub {uniqueSubId: 2, uniqueId: 2}
Sub {uniqueSubId: 3, uniqueId: 3}

The actual output is, however, all Sub's have uniqueId 1:

Org {uniqueId: 2}
Org {uniqueId: 3}
Org {uniqueId: 4}
Sub {uniqueSubId: 1, uniqueId: 1}
Sub {uniqueSubId: 2, uniqueId: 1}
Sub {uniqueSubId: 3, uniqueId: 1}

Code: var OrgCounter = 0;

var Org = function() {
    this.uniqueId = ++OrgCounter;
}

var SubCounter = 0;
var Sub = function() {
    this.uniqueSubId = ++SubCounter;
}

Sub.prototype = new Org;

console.log(new Org());
console.log(new Org());
console.log(new Org());

console.log(new Sub());
console.log(new Sub());
console.log(new Sub());

JSFiddle

qistoph
  • 78
  • 5

1 Answers1

1

You should not set the Child.prototype with an instance of Parent; especially if you don't re use the Parent constructor (Parent.call(this,...) in Child). All explained in detail here: https://stackoverflow.com/a/16063711/1641941 and here: https://stackoverflow.com/a/28574454/1641941

You should set the Child prototype with Object.create:

Sub.prototype = Object.create(Org.prototype);
Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160