Skip to content

Instantly share code, notes, and snippets.

Created July 16, 2017 16:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/e90acb7760d2ee6f014f56b91ae71c70 to your computer and use it in GitHub Desktop.
Save anonymous/e90acb7760d2ee6f014f56b91ae71c70 to your computer and use it in GitHub Desktop.
Javascript Inheritance
// 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