Last active
August 29, 2015 14:27
-
-
Save ArtemAvramenko/3d7d7b16cf20dc20885d to your computer and use it in GitHub Desktop.
Mix class with function.
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
/** | |
* Returns a function mixed with an object. | |
* @param obj - Object to mix. | |
* @param func - Target function. | |
*/ | |
function mixWithFunc<T extends Function>(obj: { __proto__?}, func: T) { | |
var objProto = <{ constructor }>obj.__proto__; | |
var objClass = <{ __mixedProto__ }>objProto.constructor; | |
var proto = <typeof obj>objClass.__mixedProto__; | |
if (!proto) { | |
proto = {}; | |
proto.__proto__ = objProto; | |
['call', 'apply', 'bind'].forEach(p => proto[p] = Function.prototype[p]); | |
objClass.__mixedProto__ = proto; | |
} | |
(<typeof obj>func).__proto__ = proto; | |
Object.getOwnPropertyNames(obj).forEach(p => func[p] = obj[p]); | |
return func; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment