Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Parasitic Combination Inheritance" in Professional JavaScript for Web Developers

Tags:

javascript

Professional JavaScript for Web Developers, Third Edition by Nicholas C. Zakas (Wrox, 2012, p.210-215 describes "Parasitic Combination Inheritance" 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 assignment of subType to the prototype.constructor does or is supposed to do. Unless I am missing something, the output I get using the example code is the same:

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

With "augment object" (prototype.constructor = subType;) in inheritPrototype http://jsfiddle.net/eAYN8/

Can this really be a line of purposeless code? Thank you for your explanation!

like image 904
Kevin Swallow Avatar asked Jun 04 '13 23:06

Kevin Swallow


2 Answers

The assignment to "constructor" is not mandatory as the assignment to "prototype" is. The reason to do it is that function prototypes usually come with the "constructor" property set by default. It might be useful for libraries that copy objects since you can get a reference to that object's constructor from the object itself.

function Foo(){
}

obj = new Foo();

console.log(obj.constructor); //function Foo
like image 153
hugomg Avatar answered Oct 24 '22 20:10

hugomg


Demo You overwrite constructor prototype so you lose SubType.prototype.constructor and if you want later to know object constructor you ought to explicitly set 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);
like image 31
Givi Avatar answered Oct 24 '22 18:10

Givi