Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Last active August 29, 2015 14:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DmitrySoshnikov/a904af6fecc191d35cc9 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/a904af6fecc191d35cc9 to your computer and use it in GitHub Desktop.
es2015-callable.js
/**
* Callable objects in ES2015.
* by Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
* 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