Created
March 23, 2015 19:26
-
-
Save dennisvennink/1f0bcfbd3da55fcd7ec4 to your computer and use it in GitHub Desktop.
Object.prototype.extend
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
Object.prototype.extend = function (object) { | |
var Constructor = object.initialize; | |
Constructor.prototype = Object.create(this.prototype); | |
Object.keys(object).forEach(function (key) { | |
if (key !== "initialize") { | |
Constructor.prototype[key] = object[key]; | |
} | |
}); | |
Constructor.prototype.constructor = object.initialize; | |
return Constructor; | |
}; | |
var Animal = Object.extend({ | |
initialize: function (species) { | |
this.species = species; | |
}, | |
walk: function () { | |
return "I'm walking!"; | |
} | |
}); | |
var Human = Animal.extend({ | |
initialize: function (name, age) { | |
Animal.prototype.constructor.call(this, "Human"); // Call to super. | |
this.name = name; | |
this.age = age; | |
}, | |
talk: function () { | |
return "My name is " + this.name + "!"; | |
} | |
}); | |
var human = new Human("Dennis", 31); | |
console.log(human instanceof Animal); // Returns true. | |
console.log(human instanceof Human); // Returns true. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment