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']();
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']();
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
.