"Parasitic Combination of Inheritance" in Professional JavaScript for Web Developers

Professional JavaScript for Web Developers, third edition of Nicholas K. Zakas (Wrox, 2012, pp. 210-215 describes "Inheritance of a parasitic combination" using the following function:

function inheritPrototype(subType, superType) { var prototype = object(superType.prototype); prototype.constructor = subType; subType.prototype = prototype; } 

I have yet to figure out what the subType assignment for prototype.constructor does or should do. If I am missing something, the output I get using the example code is the same:

Without an extension object (prototype.constructor = subType;) in inheritPrototype: http://jsfiddle.net/Q22DN/

With the "add-on object" (prototype.constructor = subType;) in inheritPrototype http://jsfiddle.net/eAYN8/

Could this be a whole series of aimless code? Thanks for your explanation!

+6
source share
2 answers

Assigning to a constructor is optional, as there is an assignment to prototype. The reason for this is that function prototypes usually have a default constructor property. This may be useful for libraries that copy objects, since you can get a link to this object constructor from the object itself.

 function Foo(){ } obj = new Foo(); console.log(obj.constructor); //function Foo 
+3
source

Demo You are rewriting the prototype of the constructor so that you lose SubType.prototype.constructor, and if you want to know the constructor of the object later, you must explicitly specify it ...

 function object(o){ function F(){} F.prototype = o; return new F(); } function inheritPrototype(subType, superType) { var prototype = object(superType.prototype); prototype.constructor = subType; //if omit (new SubType()).constructor === superType subType.prototype = prototype; } function SuperType(name){ this.name = name; } function SubType(name, age){ SuperType.call(this, name); this.age = age; } inheritPrototype(subType, superType); 
+2
source

Source: https://habr.com/ru/post/946553/


All Articles