Created
March 24, 2017 19:47
-
-
Save leo60228/8e803541fd979dab050516d4df97fe07 to your computer and use it in GitHub Desktop.
ES6 Functors
This file contains hidden or 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
class Functor { | |
constructor(...args) { | |
var self = this; | |
if (typeof this.constructor._functorlock === 'undefined') { | |
this.constructor._functorlock = true; | |
return ((functorClass) => { | |
var inst = new self.constructor(...args); | |
var out = inst.call.bind(inst); | |
for (let i of (Object.getOwnPropertyNames(inst).concat(Object.getOwnPropertyNames(Object.getPrototypeOf(inst))))) { | |
if (typeof inst[i] === "function") { | |
out[i] = inst[i].bind(inst); | |
} else { | |
out[i] = inst[i]; | |
} | |
} | |
delete out.call; | |
delete self.constructor._functorlock; | |
return out; | |
})(this.constructor); | |
} | |
} | |
} | |
class func extends Functor { | |
constructor(arg) { | |
super(...arguments); | |
this.a = arg | |
} | |
call() { | |
console.log(this.a) | |
} | |
otherfunc() { | |
console.log('hi') | |
} | |
}; | |
let inst = new func('byee'); | |
let l = console.log; | |
inst(); | |
inst.otherfunc(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment