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?

user3107531
  • 85
  • 1
  • 9
  • 2
    `this` is not what you think it is, see http://stackoverflow.com/questions/337878/var-self-this – elclanrs Jun 11 '14 at 09: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);`. – Niet the Dark Absol Jun 11 '14 at 09: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]`) – Teemu Jun 11 '14 at 09:43

1 Answers1

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);
}
Qusai Jouda
  • 1,048
  • 8
  • 12