0

I'm writing some Javascript project and have some problems with variable update. I have such a function:

function Bullet(top){
        this.top = top;     
        update();

        function update(){
            this.top -= 5;
            console.log(this.top)
            setTimeout(update, 50);
        }
};

Bullet.prototype.getTop = function(){
        return this.top;
    };

When I call:

var bullet = new Bullet(300);

I get a continuous console output of 300. Of course when I call bullet.getTop() repeatedly, I also get result 300.

Now, my questions are: Why is this happening? How do I fix it?

3
  • 2
    this is not what you think it is, see stackoverflow.com/questions/337878/var-self-this Commented Jun 11, 2014 at 9:36
  • 1
    Inside update, this is the window because there is no context given. Better to use this.update = function() { ... }; this.update(); or update.call(this);. Commented Jun 11, 2014 at 9:36
  • "a continuous console output of 300" How is that? window.top is an object, you should get a list of properties in window (or [object Window]) Commented Jun 11, 2014 at 9:43

1 Answer 1

1

"this" in the function "update" is bounded to the "update function" context not the "Bullet function" context. So, when you use "this" inside a function it does not relate to the wrapper function and when you are making changes, it applies only to the local context of the function where "this" had been used. You can read more about "this" here

You can solve the problem in two ways

The first is to call .bind(context) function when simply returns a copy of the function that had been called on but this copy is bounded to the passed context. But when you use this way you have to call the function after its definition.

this.top = top

var update = function(){
        this.top -= 5;
        console.log(this.top)
        setTimeout(update, 50);
}.bind(this)

update();

or using JavaScript closures like bellow, you define a closure call it whatever, lets say "that" and save the wrapper context in it, then use "that" inside the update function.

var that = this;
function update(){
        that.top -= 5;
        console.log(that.top)
        setTimeout(update, 50);
}
Sign up to request clarification or add additional context in comments.

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.