Skip to content
Michael Huang edited this page Mar 27, 2015 · 2 revisions

var B = function(b){this.b = b};
var F = function(f){this.f = f};

F.prototype = new B(2);
F.prototype.addF = function(){console.log(‘f’)};
B.prototype.addB = function(){console.log(‘b’)};
B.prototype.constructor = F;

var f = new F(1);

var B = function(b){this.b = b};
B.prototype.addB = function(){console.log(‘B’)};

var S = function(s){this.s = s;}
var T = function(){}

T.prototype = B.prototype;
S.prototype = new T();
S.prototype.addS = function(){console.log(‘S’)};

var s = new S(1);


sharif

Inheritance
The Original Way
function BaseClass() {}
BaseClass.prototype.aMethod = function() {}
function SubClass() {}
SubClass.prototype = new BaseClass();
● Problem is we have to create a new instance of
BaseClass before we have even created a our SubClass
instance
● What if we need to pass parameters to BaseClass?
These should be passed to our new SubClass which
then calls the BaseClass constructor (super)


Lasse Reichstein Nielsen Method
Crockford claims it as his own
function BaseClass() {}
BaseClass.prototype.aMethod = function() {}
function SubClass() {}
var TmpFn = function() {};
TmpFn.prototype = BaseClass.prototype;
SubClass.prototype = new TmpFn();

● Avoids calling new on the BaseClass
● But, remember when functions are declared, ECMA script
automatically creates a prototype object with a constructor
property pointing back to the function… One last step:

SubClass.prototype.constructor = SubClass
//Otherwise it will inherit the constructor
from BaseClass

Clone this wiki locally