0

I'm experimenting with the Google closure library and in particluar its 'inherits' method.

I have one question. When I extend a base class, if I do not set the base class's properties in its constructor, all the children end up sharing the properties, for example, if I add items to an array the array just keeps getting bigger.

Could someone explain why I need to set the properties in the constructor?

Here's my example, if you comment out "this.list = [9,8,7];" in the 'Person' constructor, the children share the persons list and keep adding to it.

http://jsbin.com/imujoy/1/edit

Thanks for any help.

aholla
  • 1

2 Answers2

0

When you reference "this.list" from the child, it first looks at the object itself to find that property. When it cannot find it, it looks at its prototype and finds the "list" array. That list, however, is a reference to the same list you created on the prototype of the Person. If you assign a new "this.list" in the constructor, you are just assigning a property on the object rather than the prototype. Generally speaking, you should not assign non-primitive types (Arrays, Objects) on the prototype if you intend to use an inheritance model because the children will share the same reference.

ne8il
  • 2,427
  • 1
  • 20
  • 18
  • A good example of assigning prototpe value properties that might be re assigned is when you set a default: Man.property.hands=2 All instances of Man and it's subclasses will have 2 hands but you can change it for the instance JerryHandy who had a little accident with the chainsaw. – HMR May 26 '13 at 10:48
0

Are you copying parent defined variables in the child using Parent.call(this) or Parent.apply

function Child(){
  Parent.apply(this,arguments);
}
goog.inherits(Child, Parent);

list becomes a property of any Child instance when defined in the Parent in the following manner:

function Parent(){
  this.list=[];
}

Basic prototype behavior:

Prototypical inheritance - writing up Good reference dealing with constructor parameters but to apply you have to implement _init and change goog.base: How to "properly" create a custom object in JavaScript?

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160