Skip to content

Instantly share code, notes, and snippets.

@andrewdacenko
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewdacenko/fe8a0df48350a2d4eb29 to your computer and use it in GitHub Desktop.
Save andrewdacenko/fe8a0df48350a2d4eb29 to your computer and use it in GitHub Desktop.
JavaScript Inheritance
function A(x) {
this.x = x;
};
A.prototype = {
log: function () {
console.log('A', this.x);
}
};
function B(x) {
A.call(this, x); // or A.apply(this, arguments)
};
B.prototype = Object.create(A.prototype, {
log: {
value: function () {
A.prototype.log.call(this);
console.log('B', this.x * this.x);
}
}
});
B.prototype.constructor = B; // save constructor, otherwise B.prototype.constructor === Object
var b = new B(10);
b.log(); // => A, 10 \n B, 10
console.log(b instanceof A); // => true
console.log(b instanceof B); // => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment