-1

I have this piece of code

var o = {
    f: function() {
        console.log(this);
    }
}

var o2 = {
    h:function(m){m()}
};

o2.h(o.f)

console prints --> window

can anyone explain why I've got windows instead of o2 ? Thanks.

Rodislav Moldovan
  • 1,025
  • 1
  • 12
  • 20

1 Answers1

6

The value of this is determined by the specifics of the actual call to a function, and nothing else. The fact that your function "f" was declared as a property of the "o" object, or that it happens to be called by a function that's got "o2" as its this value, has absolutely nothing to do with it. Because the function is ultimately called without any "receiver" object, the value of this is by default the global object (window).

If you want "f" to be called with "o" as the reference, or "o2", you can use the .bind() method that the function inherits from the Function prototype:

o2.h(o.f.bind(o2));
Pointy
  • 371,531
  • 55
  • 528
  • 584