Reputation: 7050
In this example:
var A = {test: 1, foo: function() { return this.test }}
Why A.foo()
returns 1
(at least in node.js)? I thought this
will be bound to external caller this
, no?
Upvotes: 0
Views: 144
Reputation: 163438
When you call A.foo()
, this
within foo()
is set to the object A
, as that is what you called the function on. Therefore, this.test
has a value of 1
.
You can change what this
is referenced to using .call()
or .apply()
.
A.foo.call(newThisValue);
As for why... this gives you great flexibility. You may have a function that acts on this
to do something, and the way JavaScript is built allows you to apply that function to any object
in a specific way. It is a bit hard to describe, but it does come in handy in situations such as inheritance. See also: http://trephine.org/t/index.php?title=JavaScript_call_and_apply
Upvotes: 5
Reputation: 69954
In Javascript whenever you call a function using obj.method()
notation, this
will be bound to obj
.
You can work around this by splitting the call into two separate steps:
var f = A.foo;
f(); // "this" will not be A in this case.
Or, abusing the comma operator:
(17, x.f)()
Upvotes: 1