1

This js function is part of a global variable. The first time it is called, from another js file, it works. But the second time, from itself, everything null.

 Start: function () {
   console.log('InactivityAlerts.Start() called ...');
    if (this.active) {
        if (this.IDLE_TIMEOUT != "") {
            window.setInterval(this.CheckIdleTime, 1000);
            console.log('started...');
        }
        else {
            window.setTimeout(this.Start, 1000);
             //an iframe sets the IDLE_TIMEOUT later, but this should continue to 
             //run until it is not blank.
        }
    }
},

When it calls itself again; however, everything is null, including this.active which was set from an Init prior to this. Why? And how can I make sure everything is still set right?

Thanks for any help

0

1 Answer 1

4

It's a this value issue, make sure you are binding the correct this value when passing functions around.

window.setInterval(this.CheckIdleTime.bind(this), 1000);
window.setTimeout(this.Start.bind(this), 1000);

You can also bind these at construction time if you always want them bound to the same instance.

function YourConstructor() {
    //assumes that someFunction is defined on YourConstructor.prototype
    this.someFunction = this.someFunction.bind(this);
}

Or the same with a well-known instance:

InactivityAlerts = {
    Start: function () { /*...*/ }
};

InactivityAlerts.Start = InactivityAlerts.Start.bind(InactivityAlerts);
5
  • @AdamRackis Yeah! Finally ;) I believe it's harder to get high rep these days hehe. When I see 200k+ rep users it's quite discouraging.
    – plalx
    Nov 13, 2013 at 20:11
  • Ha - well those 200K people have been here for years and years, and rack up rep on old questions without having to do much. Don't be discouraged! It took me many, many obsessive hours to hit 10K—fortunately I was in an easy job at the time :) Nov 13, 2013 at 20:15
  • Awesome! In all my years with js, I have never encountered this. Thanks again
    – password
    Nov 13, 2013 at 20:53
  • Haha, glad I could help. Is this also the case for variable properties? (ie. this.active) Or will they always reference itself correctly?
    – password
    Nov 13, 2013 at 21:10
  • @GregGamm Well the issue simply doesn't exist with non-function values. If this.active is boolean and you pass it around it will definitely stay the same in every contexts. However if you have a this.isActive function that returns this.active and you pass it around without explicitely binding the function e.g. var isActive = obj.isActive; now when you will call isActive() it will not return what you expect since this during the function execution will not be obj anymore.
    – plalx
    Nov 13, 2013 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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