Skip to content

Instantly share code, notes, and snippets.

@arccoza
Last active October 7, 2024 16:51
Show Gist options
  • Select an option

  • Save arccoza/50fe61c8430fc97a463bf6b8960776ce to your computer and use it in GitHub Desktop.

Select an option

Save arccoza/50fe61c8430fc97a463bf6b8960776ce to your computer and use it in GitHub Desktop.
JavaScript Callable Object using proxy
'use strict'
class Callable extends Function {
constructor() {
super()
return new Proxy(this, {
apply: (target, thisArg, args) => target._call(...args)
})
}
_call(...args) {
console.log(this, args)
}
}
@Kadeluxe

Copy link
Copy Markdown

It works! Very clean solution. Thank you.

@arccoza

arccoza commented Mar 12, 2021

Copy link
Copy Markdown
Author

No prob, there are other approaches to callable objects, have a look at the other gists, or this article.

@Kadeluxe

Copy link
Copy Markdown

Thanks for the link, it's a good read.

@jed

jed commented Dec 29, 2023

Copy link
Copy Markdown

you could also reuse the object itself!

class Callable extends Function {
  constructor() {
    super()    
    return new Proxy(this, this)
  }
  
  apply(...args) {
    console.log(this, args)
  }
}

@TaylorRichberger

Copy link
Copy Markdown

@jed That one has a downside in that the arguments are going to be the normal arguments to apply, rather than just the arguments you call the object with. So calling new Callable()('foo') will call apply(object, undefined, ['foo']), rather than apply('foo').

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment