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
  • 58,414
  • 16
  • 114
  • 157
Mike Shauneu
  • 3,201
  • 19
  • 21

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,436
  • 6
  • 46
  • 67
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171