I have code that looks like this:
function doStuff(args) {
// do stuff
globalFunction(foo);
}
I want to refactor my code by passing the global function in as an argument, so that if the global function changes I can just change what is passed to my function:
function doStuff(args, fn) {
// do stuff
fn(foo);
}
But for some strange reason, the function now behaves differently, and I get an error somewhere in it. I even did this to double check that I'm passing it correctly:
function doStuff(args, fn) {
// do stuff
console.log(globalFunction === fn); // true
fn(foo);
}
So I definitely know that it's the correct function. I'm really confused by this. Could someone give me an idea of what is going on?
EDIT: This just got weirder. I now have this:
function doStuff(args) {
// do stuff
globalFunction(foo); // works
const fn = globalFunction;
fn(foo); // doesn't work (???)
}
Maybe it's something specific to this function. Basically, the function is in a class, and it has references to this in its body. When I run the code normally it's fine, but when I run it from the assigned variable, I get an error where this is undefined. I would post the whole code but it's part of an external library which is huge, so I'm trying my best to summarise it.
EDIT 2:
I think I've isolated the issue. If I have code like
class foo {
a() {
console.log(this);
}
}
Then const bar = new foo(); bar.a();
logs foo
. However, if I do const fn = bar.a
and then call bar.a()
, I get undefined
. Why does this happen?