Last active
September 4, 2015 19:55
-
-
Save tobiashm/375574 to your computer and use it in GitHub Desktop.
Example of prototype inheritance in JavaScript
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' with prototype inheritance | |
function A() {} | |
A.prototype.say = function(m) { console.log('A: ' + m); }; | |
function B() {} | |
B.prototype = new A(); | |
B.prototype.say = function(m) { | |
this.constructor.prototype.say(m); | |
console.log('\nB: ' + m); | |
}; | |
new B().say('hello'); // => A: hello\nB: hello | |
// --- constructor: | |
function Foo(x) { this.x = x; } | |
function Bar(x, y) { | |
Foo.call(this, x); | |
this.y = y; | |
} | |
Bar.prototype = new Foo(); | |
new Bar(1, 2).x // => 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment