Skip to content

Instantly share code, notes, and snippets.

@leo60228
Created March 24, 2017 19:47
Show Gist options
  • Save leo60228/8e803541fd979dab050516d4df97fe07 to your computer and use it in GitHub Desktop.
Save leo60228/8e803541fd979dab050516d4df97fe07 to your computer and use it in GitHub Desktop.
ES6 Functors
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