-3

How 'this' keyword works with closure?

var a = 1000;
var b = 2000;

var obj2 = {
  a: 100,
  b: 200,
  sum: function(callback) {
    callback();
  },
  sum1: function() {
    console.log("a: " + this.a);
    console.log(this.a + this.b);
  }
};

var obj1 = {
  a: 10,
  b: 20,
  callSum: function() {
    obj2.sum(obj2.sum1);
  }
};

obj1.callSum();
j08691
  • 204,283
  • 31
  • 260
  • 272
  • 2
    Just copy/paste that into the javascript window of jsfiddle.net and you can run/play with it all you like. Your browsers console is where the answer will be so push F12 button to see it in your browser. https://jsfiddle.net/tgxoza2s/ – ekjcfn3902039 Sep 23 '19 at 18:40
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Jared Smith Sep 23 '19 at 18:43
  • This question is both too generic and too specific. You can test that code yourself and see what happens with it, and you can read a whole tutorial on how closures work for the details. – Domino Sep 23 '19 at 18:45

1 Answers1

1

Because the obj2.sum1 function is passed by reference and not being called as a member of the object, this is the global scope and not obj2.

A simpler example:

var a = "global"
var obj = {
  a: "object",
  f: function() { console.log(this.a) }
}
obj.f();    // object
var func_ref = obj.f;
func_ref(); // global

The same function is being executed in both cases. But writing obj.f() implies the binding of the context: this = obj

Jeff Ward
  • 16,563
  • 6
  • 48
  • 57