Last active
November 8, 2018 02:59
-
-
Save momocow/7660831a5c70135edded67650bc2c08e to your computer and use it in GitHub Desktop.
[Javascript] How to create a function whose name is from a variable.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"}}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.