Javascript constructor reset: What is it?

I stumbled upon this slide: http://www.slideshare.net/stoyan/javascript-patterns#postComment

on page 35:

Option 5 + super + constructor reset

function inherit(C, P) { var F = function(){}; F.prototype = P.prototype; C.prototype = new F(); C.uber = P.prototype; C.prototype.constructor = C; // WHY ??? } 

I do not understand. Can someone explain what the last line is for?

  C.prototype.constructor = C; // WHY ??? 

thanks

+6
javascript oop
source share
2 answers

This gives an explanation of http://phrogz.net/JS/Classes/OOPinJS2.html

In particular,

 Cat.prototype = new Mammal(); // Here where the inheritance occurs Cat.prototype.constructor=Cat; // Otherwise instances of Cat would have a constructor of Mammal 
+11
source share

Note: I believe that this reset is no longer needed if using # 2 of the following parameters:

I believe that you can use these options for inheritance:

* 1. done via Object.create (currently I see this syntax more often):

 Cat.prototype = Object.create(Mammal.prototype); Cat.prototype.constructor = Cat; //needed anymore?, maybe since when prototype copied its constructor needs to get re-set/changed to the child constructor 

* 2. through setPrototypeOf

 Object.setPrototypeOf(Cat.prototype, Mammal.prototype); //don't need to reset Cat.prototype.constructor in this case; 'seems smarter' 

* 3. through a new one; I do not think that this method is recommended anymore (although this is exactly how I learned to establish inheritance many years ago). I believe that reading prototype settings this way using 'new ParentClass ()' is no longer recommended, as it will copy properties that are not needed in the prototype, I believe (the properties that you usually set in an instance with super (constructorParams) or ParentClass.call (this, constructorParams) in the Cat constructor / function, so they should be shared by all instances through the prototype).

 Cat.prototype = new Mammal(); Cat.prototype.constructor=Cat; 
0
source share

All Articles