decarte
decarte

Reputation: 420

Why this "this" behavior?

Hello I am stuck on a case I don't get

here is the code

function car(speed) {
    this.speed = speed; 
    this.accelerate = function() {
        this.speed += 1;
    }
}

var oldcar = new car(1);

function test(cb){
  cb();
}

test(oldcar.accelerate);

console.log(oldcar.speed);
// 1

test(function(){ oldcar.accelerate(); });

console.log(oldcar.speed);
// 2

On the first function call test(), I observe that the this in the oldcar.accelerate method is set to window.

On the second case, the this is correctly set to oldcar.

I don't understand how calling test() with oldcar.accelerate instead of function(){ oldcar.accelerate(); } make such a difference.

Can someone explain the behavior ? thanks !

Upvotes: 1

Views: 73

Answers (1)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

Because when you pass a method as a callback you are passing only the method, not the object which it belongs to.

When this is used in without any given scope, it defaults to window (or the closest surrounding scope).

A correct way is to pass the entire object, or an anonymous function has has access to the entire object..

function test(cb){
  cb();
}

test(function(){ oldcar.accelerate() });

Upvotes: 1

Related Questions