Skip to content

Instantly share code, notes, and snippets.

@c7x43t
Last active June 22, 2018 11:08
Show Gist options
  • Save c7x43t/8b655ba3543fd046b3c31535e7343d6b to your computer and use it in GitHub Desktop.
Save c7x43t/8b655ba3543fd046b3c31535e7343d6b to your computer and use it in GitHub Desktop.
// subClass returns a constructor wrapper function that has all the methods in the subclass Prototype,
// while keeping the original return type's prototype
// when to use? augmenting objects generated by classes with methods.
// since it is a wrapper also native classes like Array, String, Number can safely be extended
// adding methods to returned objects is also reasonably fast this way, because only the Prototype needs to be set
function subClass(constructor, returnType, methods) {
function collector() {}
methods = methods ? methods instanceof Array ? methods : [methods] : [];
const subConstructor = function() {
const obj = constructor(...arguments);
Object.setPrototypeOf(obj, collector.prototype);
return obj;
};
Object.defineProperty(subConstructor, "name", {
value: constructor.name
}); // not necessary
collector.prototype = Object.create(returnType.prototype);
collector.prototype.constructor = subConstructor;
for (var method of methods) collector.prototype[method.name] = method;
subConstructor.prototype = Object.create(collector.prototype);
return subConstructor;
}
// Example: subVerboseArray will augment the Array returned by verboseArray with the method a.
function verboseArray(arr) {
return arr;
}
function a(x) {
return x + 1;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var subVerboseArray = new subClass(verboseArray, Array, a);
console.log(subVerboseArray(arr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment