Skip to content

Instantly share code, notes, and snippets.

@dennisvennink
Created March 23, 2015 19:26
Show Gist options
  • Save dennisvennink/1f0bcfbd3da55fcd7ec4 to your computer and use it in GitHub Desktop.
Save dennisvennink/1f0bcfbd3da55fcd7ec4 to your computer and use it in GitHub Desktop.
Object.prototype.extend
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