I have an arrow function:
() => 'a'
Can I name this function by one of my variable, such that:
let func_name = 'a';
// expected output
// let a = () => 'a';
I have an arrow function:
() => 'a'
Can I name this function by one of my variable, such that:
let func_name = 'a';
// expected output
// let a = () => 'a';
It is possible. Since everything, except for primitive types, is an object in JavaScript, you can do:
The not so right way, which is polluting the global or current namespace:
function func(){
// func is an object, see Functions on MDN
let func_name = 'a';
this[func_name] = () => func_name;
// To call it
console.log(
this[func_name]()
);
}
func();
// func is an object, see Functions on MDN
let func_name = 'a';
// Object.freeze, so obj cannot be changed, similar to const
// Object.seal, the structure cannot be changed.
const obj = Object.freeze({
[func_name]: () => func_name
})
obj[func_name] = "aaaaa"; // Throws an error in strict mode
// To call it
console.log(obj[func_name]());
Bear in mind that you can always reassign obj[func_name]
to anything. Depending on the implementation, you can use Object.seal
or Object.freeze