Last active
August 29, 2015 14:03
-
-
Save jeffschwartz/c0671aa3b2873f33d84d to your computer and use it in GitHub Desktop.
Emulates classical inheritance and results in a prototype chain (nested prototypes) of base classes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Emulates classical inheritance and results in a | |
* prototype chain (nested prototypes) of baseclasses. | |
*/ | |
(function(){ | |
/* | |
* Extend childObj from parentObj and apply childPrototype to the childObj. | |
* @param {Objectl} childObj The child object. Required. | |
* @param {Objectl} parentObj The parent object. Required. | |
* @param {Objectl} childPrototype An object whose properties are used to extend childObj's prototype. Optional. | |
*/ | |
function extendObject(childObj, parentObj, childPrototype){ | |
var tmpObj = function(){}, | |
prop; | |
tmpObj.prototype = parentObj.prototype; | |
childObj.prototype = new tmpObj(); | |
//***Important*** Maintain the prototype's "constructor' | |
//property so that "instanceof" will function properly. | |
childObj.prototype.constructor = childObj; | |
//If childPrototype was passed then extend child.prtotype with its properties. | |
if(childPrototype){ | |
for(prop in childPrototype){ | |
childObj.prototype[prop] = childPrototype[prop]; | |
} | |
} | |
} | |
function BaseClass(arg){ | |
this.abc = arg; | |
} | |
BaseClass.prototype.doSomething = function(){ | |
console.log('abc =', this.abc); | |
} | |
//Derived from BaseClass | |
function A(arg){ | |
//Since we inherit from BaseClass, call BaseClass constructor using "this". | |
BaseClass.call(this, arg); | |
} | |
var aPrototype = { | |
doSomethingA: function doSomethingA(){ | |
console.log('doSomethingA called'); | |
} | |
}; | |
extendObject(A, BaseClass, aPrototype); | |
var a = new A('abc'); | |
//Call inherited method. | |
a.doSomething(); | |
//Call its own method. | |
a.doSomethingA(); | |
//Validate that instanceof is functioning correctly. | |
console.log(a instanceof(A)); | |
console.log(a instanceof(BaseClass)); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment