Created
June 18, 2011 16:41
-
-
Save juandopazo/1033258 to your computer and use it in GitHub Desktop.
Function.create for inheritance
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
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!! |
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
(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