Skip to content

Instantly share code, notes, and snippets.

@agostbiro
Last active August 29, 2015 14:17
Show Gist options
  • Save agostbiro/4246546bac2548ded92b to your computer and use it in GitHub Desktop.
Save agostbiro/4246546bac2548ded92b to your computer and use it in GitHub Desktop.
Simple JavaScript prototypal inheritance with the 'new' keyword
function A()
{
this.a = 'a';
}
A.prototype.foo = function foo()
{
console.log('foo');
};
function B()
{
A.call(this);
this.b = 'b';
}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
B.prototype.bar = function bar()
{
console.log('bar');
};
function C()
{
A.call(this);
B.call(this);
this.c = 'c';
}
C.prototype = Object.create(B.prototype)
C.prototype.constructor = C;
C.prototype.baz = function baz()
{
console.log('baz');
};
function test(Testee)
{
var tester = new Testee();
console.log(tester.a, tester.b, tester.c);
tester.foo && tester.foo();
tester.bar && tester.bar();
tester.baz && tester.baz();
console.log(tester.constructor)
}
test(A);
test(B);
test(C);
/*
Prints:
>> a undefined undefined
>> foo
>> [Function: A]
>> a b undefined
>> foo
>> bar
>> [Function: B]
>> a b c
>> foo
>> bar
>> baz
>> [Function: C]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment