Created
September 13, 2019 05:27
-
-
Save jonathantneal/f8a0366d4685590b5b3181b768589f74 to your computer and use it in GitHub Desktop.
An ES5 Class Creator
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
// 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; | |
} |
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
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