4

I'm trying to break logic into a few separate chunks, but hitting a snag. The basic structure of my helper looks like:

({
    foo: function (component) {
        console.log(this.bar); // <-- undefined
        window.setTimeout(function () {
            this.bar(someValue);
        }, 12345);
    },
    bar: function (someArgument) {
        console.log("bar"); // <-- not called
    }
})

When I am in foo, why is this.bar undefined? Why does my timeout not call bar? If it is actually undefined, shouldn't I get an error for undefined is not a function? I tried inverting the order of the function definitions just to see if you can only call functions in this way if they are defined further up in the file, but it did not change the behavior.


Turns out my initial example was overly simplified. What I actually had was more like:

foo: function (component, tabId) {
    // here is where I need to cache this
    component.find("workspaceAPI").getTabInfo({
        tabId: tabId
    }).then(function (response) {
        this.bar(someValue);
        // this no longer references the helper
    })
}
4

window.setTimeout will run in a Global Context and thus this will point to that context. To be able to utilize this in Function Context (which is foo in this case), you will need to assign the local context prior to calling setTimeout and then utilize it as below:

foo: function (component) {
    var myLocalThis = this; // capture the local context
    window.setTimeout(function () {
        myLocalThis.bar(someValue); // use the local context this here
    }, 12345);
},

Related Links:

| improve this answer | |
  • A nice explanation for setTimeout "this" issues is available in the mozilla docs. Personally, I'd use bind to set up a bound version of the function with the required this reference. – Phil W May 28 '19 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.