Skip to content

Instantly share code, notes, and snippets.

@shesek
Last active January 14, 2019 15:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shesek/4636379 to your computer and use it in GitHub Desktop.
Save shesek/4636379 to your computer and use it in GitHub Desktop.
Decorate constructor functions, and have them return a callable object that delegates to a `callable()` method when invoked.
##########
### Moved to https://github.com/shesek/callable-klass
##########
"use strict"
# without strict mode, `this` defaults to window, so `(this?obj)`
# would always return window.
callable = (ctor) ->
callable_ctor = (a...) ->
obj = -> obj.callable.apply (this ? obj), arguments
obj.__proto__ = ctor::
result = ctor.call obj
if typeof result is 'object' then result
else obj
callable_ctor.__proto__ = ctor
callable_ctor:: = ctor::
# Copy call() and apply() from Function.prototype to the constructor prototype
{call: callable_ctor::call, apply: callable_ctor::apply} = Function::
callable_ctor
module.exports = callable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment