Why do parentheses keep this when called in the same expression

Consider the following variables:

var obj = {
    value    : 'from object',
    getValue : function() { return this.value; }
};

var value = 'from global';

      

It obj.getValue()

is now evaluated as 'from object'

. And if I only get a reference to the getValue function and call it:

var f = obj.getValue;
f();

      

f matters 'from global'

.

My question is, why does it (obj.getValue)();

return 'from object'

?

I would have thought that the first set of parentheses would evaluate an equal reference to the getValue function, and then when that result this

is called, it will be the global context. Why does the interpreter assume that this is a call to an object?

+3


source to share


1 answer


When you call var f = obj.getValue();

, you run the method getValue

from the object. When you call var f = obj.getValue;

, you reassign the function f

, and then when you call f

, it has no relation obj

, it is simply called a global function.



+1


source







All Articles