Last active
August 29, 2015 14:26
-
-
Save DmitrySoshnikov/a904af6fecc191d35cc9 to your computer and use it in GitHub Desktop.
es2015-callable.js
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
/** | |
* Callable objects in ES2015. | |
* by Dmitry Soshnikov <[email protected]> | |
* MIT Style License | |
*/ | |
class Callable extends Function { | |
constructor() { | |
super('(' + Callable.prototype.__call__ + ')();'); | |
return this.bind(this); | |
} | |
// Notice, this method cannot have free variables, | |
// because functions, created by the `Function` | |
// constructor aren't actual closures (they capture | |
// only global environment). | |
__call__() { | |
return this.method(); | |
} | |
method() { | |
console.log(1); | |
} | |
} | |
var c = new Callable(); | |
c(); // 1 | |
// or simply :P | |
c.__call__(); | |
// Alternative way to create a callable object, is to use Proxies, | |
// but even then, a target should be a callable object as well. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment