Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Created September 13, 2019 05:27
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 jonathantneal/f8a0366d4685590b5b3181b768589f74 to your computer and use it in GitHub Desktop.
Save jonathantneal/f8a0366d4685590b5b3181b768589f74 to your computer and use it in GitHub Desktop.
An ES5 Class Creator
// 281 bytes:
/** Return a class with prototype values conditionally inheriting from a super class
* @param {string} name name of the class
* @param {Object<string,any>} prototype prototype values of the class
* @param {Function} [Super] super class inherited by the class
* @return {Function}
*/
function _class(name, prototype, Super) {
var Class = Function('_', 'return function ' + name + '(){return _(this,arguments)}')(
function (c,a) {
return this.apply(c,a) || c;
}.bind(
Object.hasOwnProperty.call(prototype, 'constructor') ? prototype.constructor : function() {
if (Super) {
Super.call(this, arguments);
}
}
)
);
Class.prototype = Object.create(
(Super ? (Class.__proto__ = Super) : Class).prototype,
{
constructor: {
configurable: true,
value: Class,
writable: true
}
}
);
Object.keys(prototype).forEach(function (name) {
if (name !== 'constructor') {
Object.defineProperty(Class.prototype, name, {
configurable: true,
value: prototype[name],
writable: true
});
}
});
return Class;
}
Sup = _class('Sup', {
constructor () {
console.log('new Sup()', arguments.length)
},
supness() {
return 'supness'
}
});
Sub = _class('Sub', {
constructor () {
console.log('new Sub()', arguments.length);
this.constructor.__proto__.apply(this, arguments);
},
subness() {
return 'subness'
}
}, Sup);
sub = new Sub(5, 2, 9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment