Skip to content

Instantly share code, notes, and snippets.

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