Skip to content

Instantly share code, notes, and snippets.

@catdad
Last active August 29, 2015 14:25
Show Gist options
  • Save catdad/ec050868f3de246bd482 to your computer and use it in GitHub Desktop.
Save catdad/ec050868f3de246bd482 to your computer and use it in GitHub Desktop.
... because this is the right answer when asked about JavaScript inheritance
function inherit(proto) {
function F() {};
F.prototype = proto;
return new F;
// Note: use `Object.create` instead of `inherit` if you do not need to support old browsers
}
// create any "class"
function A() {
// create A-specific instance members
this.propOfA = 'a';
}
A.prototype.performA = function(){ console.log('performA'); };
// create another "class"
function B() {
// inherit instance members
A.call(this);
// instance members of B
this.propOfB = 'b';
}
// inherit from A -- pick one
// for old browsers (and new ones)
B.prototype = inherit(A.prototype);
// for new browsers (better option)
B.prototype = Object.create(A.prototype);
// create B-specific methods
B.prototype.performB = function(){ console.log('performB'); };
// usage
var a = new A();
var b = new B();
a instanceof A; // true
a instanceof B; // false
b instanceof A; // true
b instanceof B; // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment