0

I have an async function:

async function f() {
   ...
}

Also I have object to store functions:

const functions = {};
functions['f'] = f;

Is there differences between?

await f();

and:

await functions['f']();
isherwood
  • 52,576
  • 15
  • 105
  • 143
Mike Shauneu
  • 3,013
  • 16
  • 20

1 Answers1

4

There is a difference in the value of this. When calling the function as a method, this will be the object it was called on. Otherwise it will be the global object, or undefined in strict mode.

(async function() {

async function f() {
  console.log(this === functions);
}

const functions = {};
functions['f'] = f;

await f();

await functions['f']();

})();

For further information see MDN on this.

To force the context of the "independent" function, you could bind() the function to the original object:

const f = functions.f.bind(functions);

Now, when f() is called this would always be functions.

try-catch-finally
  • 7,061
  • 6
  • 40
  • 65
Alexander O'Mara
  • 56,044
  • 17
  • 157
  • 163