1

Have following code.

object.waypoint=function () {
    this.uw=setInterval( function() {
       console.log(this);
    }, 200);
}

How do I refer to "object" inside function on line three, I tried it with "this" keyword but it doesn't seem to refer the object.

0

3 Answers 3

1

Inside setInterval this refers to window. You'll need to make a variable that references to this.

object.waypoint=function () {
    var me = this;

    this.uw=setInterval( function() {
       console.log(me);
    }, 200);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I tried that already but didn't insert "var" keyword, this one works. :)
@Otto-VilleLamminpää Please accept an answer if you found the solution to your question.
1

A common way is to store a reference to this in a variable, that you then can use to get access to the proper this:

object.waypoint=function () {
    // Keep a reference to this in a variable
    var that = this;
    that.uw=setInterval( function() {
       // Now you can get access to this in here as well through the variable
       console.log(that);
    }, 200);
}

Comments

0

I think bind is a neat solution - It isn't implemented in all browsers but there are workarounds.

object.waypoint = function(){
    this.uw = setInterval(function(){
        console.log(this);
    }.bind(this), 200);
}

See the MDN page for proper documentation

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.