I wonder why the code below returns undefined instead of 5:

var f = function() { this.x = 5; (function() { this.x = 3; })(); console.log(this.x); }; var obj = {x: 4, m: function() { console.log(this.x); }}; obj.m.call(f); 

    1 answer 1

    Feel the difference between

     obj.m.call(f); 

    and

     obj.m.call(new f); 

    In the first case, you pass the function, and in the second, the object.

    • Not quite clear. That is, a function in the context of another function cannot be called? But the function in js is an object ... - andreyqin
    • one
      @andreyqin wait. Everything is much easier. Roughly speaking, when you create an object using new, then using call you pass the object along with all the guts :). And in your case, you pass only the function, i.e. this in obj.m will contain a function that can be called like this() :. And since is a function, not an object, then the value of this.x changed only in the passed function f() . Here, probably something like that. - lampa