-
-
Save linuxenko/3f6b28fed27bd291b88862ccb719d67f to your computer and use it in GitHub Desktop.
Function.prototype.extend for simple classes in ES5
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
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; | |
}; |
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
// 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