Domanda

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

È stato utile?

Soluzione

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();

Altri suggerimenti

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.

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).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top