Last active
August 29, 2015 14:04
-
-
Save Kichrum/fa80aa9f20df2b0d3584 to your computer and use it in GitHub Desktop.
Inheritance in JavaScript for EcmaScript 3
This file contains hidden or 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
/** | |
* One more version of inheritance for ES3 | |
* @author Kichrum | |
*/ | |
var inherit = function(Parent) { | |
var Child = function(){ Parent.apply(this, arguments) } | |
// We can use | |
// Child.prototype = Object.create(Parent.prototype) | |
// here for ES5 instead of next 3 lines: | |
var F = function() {} | |
F.prototype = Parent.prototype | |
Child.prototype = new F() | |
return Child | |
} | |
var Animal = function(name) { this.name = name } | |
Animal.prototype.say = function() { console.log('an ' + this.name) } | |
var Dog = inherit(Animal) | |
Dog.prototype.say = function() { console.log('dog ' + this.name) } | |
var a = new Animal('a') | |
var b = new Dog('b') | |
a.say() | |
b.say() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment