Reputation: 7805
I would expect a function's context (this
) to be the same as its parent/scope. Should it not be so?
Check the example under, I would expect _context
to get the value of Object {foo: "bar"}
, but instead I get window
object.
Where is my logic cheating me?
var context = {
foo: 'bar'
};
var _context;
var fn = (function () {
console.log(this); // Object {foo: "bar"}
function foo() {
_context = this;
}
foo();
}.bind(context))();
console.log(_context); // window?! why?
jsFiddle: http://jsfiddle.net/1nz4dda3/
Upvotes: 0
Views: 58
Reputation: 147363
A function's this is set by how it's called, or by bind. ECMAScript 2015 arrow functions get their this from the surrounding execution context.
The this value isn't "context", it just one parameter of a function's execution context.
When you do:
var fn = (function () {
...
}.bind(context))();
you are binding the object context to the IIFE's this. However, when you call:
foo();
you haven't set its this parameter, so it will default to the global object (window in a browser). In strict mode, it will be undefined. It does not matter where you call foo from, it's how you call it that sets its this.
Upvotes: 1
Reputation: 23778
You are calling the function plainly in the window
context by calling foo()
. In JS this
refers to the calling context and it doesn't matter where any function is written inside.
Here is a good article about JS method context.
http://helephant.com/2009/11/29/javascript-method-context/
Upvotes: 1