0

I am learning javascript but I have some doubts about functions/closures, i have this code:

var obj = { value: 0 };

obj.test = function() {

    var that = this;

    var f1 = function() {

        console.log(that);
    };

    f1();


};

obj.test();

var x = obj.test;

x();

I know that when a function is invoked like f() this refer to the global object but in my example when f1 is defined it has a reference that to the this of the outer function that refer to obj. I expect that the function remember the context in which it was created so why the last call x() refers to the global object?

Thanks

res1
  • 2,882
  • 4
  • 25
  • 40

3 Answers3

3

I expect that the function remember the context in which it was created

That right there is your mistake. JavaScript functions do not "remember" any relationship to any particular object in a case like that. The only things they remember are in-scope variables in the chain of parent lexical contexts. In this case, the "obj" variable is such a variable.

You can explicitly create a function that remembers a relationship to an object with the .bind() method.

obj.boundTest = obj.test.bind(obj);

var x = obj.boundTest;
x(); // will do the right thing

or even more simply:

var x = obj.test.bind(obj);
x();
Pointy
  • 371,531
  • 55
  • 528
  • 584
  • I like your suggestion of using bind here, it is a good way to maintain a connection back to the context. – Travis J Apr 17 '14 at 14:17
2

I expect that the function remember the context in which it was created

It doesn't.

Context is determined by how a function is called and only by how a function is called.

You are calling it in the global context, so this is the global object.

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

The reason for this occurring is that when you make a copy of that function

var x = obj.test;

you are only copying the function. Not the object, nor any of its variables. So when you attempt to run x (which is obj.test) it runs fresh. The result is that this is re-evaluated which now refers to the global context (or undefined in strict mode).

Travis J
  • 77,009
  • 39
  • 185
  • 250