Skip to content

Instantly share code, notes, and snippets.

@juandopazo
Created November 15, 2011 14:21
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save juandopazo/1367191 to your computer and use it in GitHub Desktop.
Save juandopazo/1367191 to your computer and use it in GitHub Desktop.
Function.prototype.extend for simple classes in ES5
Object.getOwnPropertyDescriptors = function getOwnPropertyDescriptors(obj) {
var descriptors = {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
descriptors[prop] = Object.getOwnPropertyDescriptor(obj, prop);
}
}
return descriptors;
};
Function.prototype.extend = function extend(proto) {
var superclass = this;
var constructor;
if (!proto.hasOwnProperty('constructor')) {
Object.defineProperty(proto, 'constructor', {
value: function () {
// Default call to superclass as in maxmin classes
superclass.apply(this, arguments);
},
writable: true,
configurable: true,
enumerable: false
});
}
constructor = proto.constructor;
constructor.prototype = Object.create(this.prototype, Object.getOwnPropertyDescriptors(proto));
return constructor;
};
// Object is a function, so it gets extend()
// That means Object.extend() creates a new constructor function
// with .prototype.__proto__ === Object.prototype
var Person = Object.extend({
constructor: function Person(name) {
this.name = name;
},
say: function (message) {
return this.name + ' says: ' + message;
}
});
var Pirate = Person.extend({
say: function (message) {
//lack of super makes this very verbose :(
return 'Capt\'n ' + Object.getPrototypeOf(Pirate.prototype).say.apply(this, arguments) + ' arrr!';
}
});
var blackbeard = new Pirate('Blackbeard');
console.log(blackbeard);
console.log(blackbeard.say('ahoy!'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment