Skip to content

Instantly share code, notes, and snippets.

@monolithed
Forked from DmitrySoshnikov/es2015-callable.js
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monolithed/b6c8f6c4912f0744cb46 to your computer and use it in GitHub Desktop.
Save monolithed/b6c8f6c4912f0744cb46 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