Created
July 16, 2017 16:38
-
-
Save anonymous/e90acb7760d2ee6f014f56b91ae71c70 to your computer and use it in GitHub Desktop.
Javascript Inheritance
This file contains 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
// Super Base Class | |
function SuperBase() {} | |
// Base class | |
function Base(spec) { | |
this.name = spec.name; // Define the "name" property | |
} | |
// Child class | |
function Child(spec) { | |
Base.call(this, spec); // Call the base class constructor | |
} | |
// Wire prototypes | |
function F2() {} // This F is a temporary function not part of the chain. | |
F2.prototype = SuperBase; | |
const intermediateObj2 = new F2(); | |
Base.prototype = intermediateObj2; // This is where we put superclass methods | |
console.assert(Base.prototype.__proto__ === SuperBase) | |
// Wire prototypes | |
function F() {} // This F is a temporary function not part of the chain. | |
F.prototype = intermediateObj2; | |
const intermediateObj = new F(); | |
Child.prototype = intermediateObj; // This is where we put superclass methods | |
console.assert(Child.prototype.__proto__ === intermediateObj2) | |
// Add methods to delegate | |
intermediateObj.sayHello = function () { // Define the "sayHello" method | |
return 'Hello, I\'m ' + this.name; | |
}; | |
// Add methods to super delegate | |
intermediateObj2.sayHello2 = function () { // Define the "sayHello" method | |
return '!!!!!!!!!!!!!!!'; | |
}; | |
// Usage | |
const object = new Child({ name: 'a prototypal object' }); | |
console.assert(object.__proto__ === intermediateObj) | |
console.assert(object.__proto__.__proto__ === intermediateObj2) | |
console.assert(object.__proto__.__proto__.__proto__ === SuperBase) | |
object.sayHello(); // 'Hello, I\'m SuperBase' | |
object.sayHello2(); // '!!!!!!!!!!!!!!!' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment