3

Consider the following variables:

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

var value = 'from global';

Now, obj.getValue() evaluates to 'from object'. And if I get a reference to just the getValue function and call it:

var f = obj.getValue;
f();

f evaluates to 'from global'.

My question is why does (obj.getValue)(); return 'from object'?

I would have thought that the first set of parenthesis would evaluate to a plain reference to the getValue function and then when calling that result, this would be the global context. Why does the interpreter assume this is a call on the object?

Patrick
  • 43
  • 5

1 Answers1

1

When you call var f = obj.getValue();, you are running the getValue method from the object. When you call var f = obj.getValue;, you are reassigning the function to f, and then when you call f, it has no ties to obj, it is simply called as a global function.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76