Skip to content

Instantly share code, notes, and snippets.

@momocow
Last active November 8, 2018 02:59
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 momocow/7660831a5c70135edded67650bc2c08e to your computer and use it in GitHub Desktop.
Save momocow/7660831a5c70135edded67650bc2c08e to your computer and use it in GitHub Desktop.
[Javascript] How to create a function whose name is from a variable.
function factory (name, fn) {
const scope = {
// wrapper
[name] (...args) {
return fn(...args)
}
}
return scope[name]
}
const fn = factory('test', (...args) => console.log('This is a test(%s)', args.map(JSON.stringify).join(', ')))
console.log(fn)
// [Function: test]
fn(1, [ 2, 3 ], { test: true, nested: { text: 'yes' } })
// This is a test(1, [2,3], {"test":true,"nested":{"text":"yes"}})
@momocow
Copy link
Author

momocow commented Nov 8, 2018

To create a function whose name is from a variable, the trick is to make use of both the shorthand method name and the computed property name defined in ES6.

See Object Initializer (MDN Page) if you are not familiar with it.

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