0

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';       
Adam Azad
  • 11,171
  • 5
  • 29
  • 70
duck
  • 141
  • 1
  • 9

1 Answers1

0

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

Adam Azad
  • 11,171
  • 5
  • 29
  • 70
  • 3
    I'd advise against adding random values to `this`. In the current code, `this` is going to be `window`, so you're actually making all of these global. It makes it very likely that something will clash. Worse yet, if strict mode is enabled, this code will fail because `this` would be set to `undefined` and thus you'd get an error for trying to set a property on it. – VLAZ Oct 02 '20 at 05:50
  • @VLAZ, that's why I recommended another implementation; like `obj = { [func_name]: () => func_name }`. – Adam Azad Oct 02 '20 at 05:55
  • @AdamAzad but why use `this` at all if it's not recommended even by you? – VLAZ Oct 02 '20 at 06:13