Skip to content

Instantly share code, notes, and snippets.

@juandopazo
Created July 1, 2011 12:50
Show Gist options
  • Select an option

  • Save juandopazo/1058478 to your computer and use it in GitHub Desktop.

Select an option

Save juandopazo/1058478 to your computer and use it in GitHub Desktop.
Proto, a Selfish variant
////////// API //////////
// Code by Axel Rauschmayer
// Based on Selfish https://github.com/Gozala/selfish
// To be part of ECMAScript.next
if (!Object.getOwnPropertyDescriptors) {
Object.getOwnPropertyDescriptors = function (obj) {
var descriptors = {};
Object.getOwnPropertyNames(obj).forEach(function (prop) {
descriptors[prop] = Object.getOwnPropertyDescriptor(obj, prop);
});
return descriptors;
};
}
var Proto = {
new: function () {
// new this.constructor() does not let us hand in the arguments
// => we have to simulate it
var instance = Object.create(this);
if (instance.constructor) {
instance.constructor.apply(instance, arguments);
}
return instance;
},
extend: function (props) {
// We cannot set the prototype of "properties"
// => copy them to a new object that has the right prototype
var subProto = Object.create(this, Object.getOwnPropertyDescriptors(props));
// Ensure that constructor and prototype point to each other
if (subProto.constructor) {
subProto.constructor.prototype = subProto;
}
subProto.super = this; // for super-calls
return subProto;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment