Skip to content

Instantly share code, notes, and snippets.

@juandopazo juandopazo/main.js
Created Jun 18, 2011

Embed
What would you like to do?
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
You can’t perform that action at this time.