0

I understand that there are quite a few question similar to this one but I couldn't find any which answers why or may how the context(value) of this changes when a callback function is called from inside the object function like this

var obj = {
           objproperty: "this is a property of obj",
           func1: function(x,cb){
                  console.log(this) // refers to obj
                  var output_value = x + 20;
                  cb(output_value);
           }
          };

obj.func1(123,function(output_value){
console.log(output_value);
console.log(this); // does this refers to window or undefined??
});

as far as I understand the value shouldn't 'this' in third console.log be referring obj? as it called on the obj Object ?

level0
  • 283
  • 1
  • 3
  • 13

2 Answers2

1

as it called on the obj Object ?

No, it isn't.

cb(output_value);

There is nothing to the left of cb so it is called in the default context.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
1

Your callback is called like this:

  cb(output_value);

There's no object context in that function call, so the value of this will be either window (or the global context) in non-strict mode, or undefined in strict mode.

If you want to make sure that the callback has a this value that matches that in the context in which it's called, you can use .call():

cb.call(this, output_value);
Pointy
  • 371,531
  • 55
  • 528
  • 584