Skip to content

Instantly share code, notes, and snippets.

@juandopazo
Created June 18, 2011 16:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juandopazo/1033258 to your computer and use it in GitHub Desktop.
Save juandopazo/1033258 to your computer and use it in GitHub Desktop.
Function.create for inheritance
var Person = Function.create(null, {
constructor: function (name) {
this.name = name;
},
say: function (message) {
return this.name + ' says: ' + message;
}
});
var Pirate = Person.extend({
constructor: function (name) {
Pirate.superclass.constructor('Capt\'n ' + name);
},
say: function (message) {
return Pirate.superclass.say(message) + ' Arr!!';
}
});
var blackbeard = new Pirate('Blackbeard');
console.log(blackbeard.say('Ahoy, me mateys!')); // Capt'n Blackbeard says: Ahoy, me mateys! Arr!!
(function () {
function getOwnPropertyDescriptors(obj) {
var descriptors = {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
descriptors[prop] = Object.getOwnPropertyDescriptor(obj, prop);
}
}
return descriptors;
}
Function.create = function (superclass, proto) {
var constructor = proto.constructor;
if (!constructor) {
constructor = proto.constructor = function () {};
}
constructor.prototype = Object.create(superclass ? superclass.prototype : {}, getOwnPropertyDescriptors(proto));
if (superclass) {
constructor.superclass = superclass.prototype;
}
return constructor;
};
Function.prototype.extend = function (proto) {
return Function.create(this, proto);
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment