Skip to content

Instantly share code, notes, and snippets.

@johnjbarton
Created November 14, 2011 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnjbarton/1365284 to your computer and use it in GitHub Desktop.
Save johnjbarton/1365284 to your computer and use it in GitHub Desktop.
Refactoring of Irakli Gonzala's extend() from git://gist.github.com/1361599.git
Object.defineProperty(Object, 'mergeDescriptors', {
value: function() {
// Shallow copy of the argument property descriptors, right most wins
//
var properties = {}
Array.prototype.slice.call(arguments).forEach(function(source) {
Object.getOwnPropertyNames(source).forEach(function(name) {
properties[name] = Object.getOwnPropertyDescriptor(source, name)
})
})
return properties;
}
});
Object.defineProperty(Object, 'subclass', {
value: function(prototype, statics) {
var constructor = function () {
// |instance| ProtoLink points to |statics.prototype| points to |this.prototype|
var instance = Object.create(prototype)
// |initialize| becomes special; presumably Function.prototype.initialize is defn empty.
prototype.initialize.apply(instance, arguments)
return instance
}
// constructor prototype chains this.prototype; properties from shallow merger
//
Object.defineProperties(constructor, statics)
return constructor
}
});
Object.defineProperty(Object, 'extend', {
value: function() {
var properties = Object.mergeDescriptors.apply(null, arguments);
var statics = {}
// The property descriptors from |this|
//
Object.getOwnPropertyNames(this).forEach(function(name) {
if (!(name in Function.prototype))
statics[name] = Object.getOwnPropertyDescriptor(this, name)
}, this)
// ProtoLink to |this.prototype| (if any); properties from shallow merger
var prototype = statics.prototype = Object.create(this.prototype, properties)
return Object.subclass(prototype, statics);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment