Reputation: 6399
I am reading this chapter in You don't know JS .
function baz() {
// call-stack is: `baz`
// so, our call-site is in the global scope
console.log("baz");
bar(); // <-- call-site for `bar`
}
function bar() {
// call-stack is: `baz` -> `bar`
// so, our call-site is in `baz`
console.log("bar");
foo(); // <-- call-site for `foo`
}
function foo() {
// call-stack is: `baz` -> `bar` -> `foo`
// so, our call-site is in `bar`
console.log("foo");
console.log(this);
}
baz(); // <-- call-site for `baz`
I was expecting the console.log(this)
in function foo
to print bar
, since bar
is the call site, but instead it seems to be window
.
How is the this
reference window
instead of bar
inside the function foo ?
Upvotes: 0
Views: 115
Reputation: 13
It is true that 'bar' is the call site but you have to see which of the 4 rules apply to the call-site. In this case, there is no new
binding. Similarly we do not see either hard, explicit or implicit binding since the foo()
is not executed as obj.foo()
. Thus it is a clear case of default binding hence this
points to the global object i.e. window
Upvotes: 0
Reputation: 2737
As explained wonderfully by Kyle Simpson, the value of this
depends on only 4 conditions depending on the call site:
var obj = {
foo: function() {
console.log(this);
}
};
function foo() { console.log(this); }
1. Call using object(Implicit binding)
obj.foo();
In this case, foo
is called using obj
(always notice the object before the dot operator). Hence this
refers to obj
inside foo
.
2. 'call' or 'apply' (Explicit binding)
foo.call(obj);
Here, this
inside the function foo
refers to obj
since it has been binded explicitly.
3. Call using new (new keyword)
obj = new foo();
Inside foo, this
now refers to the newly created object.
4. Global object (Default Binding)
foo();
Here, foo
is called directly. Hence it defaults to window
. (This is your case!)
As you can see, in your case, foo
is called directly(case 4). Hence this
refers to the window
object. Just remember these 4 cases and you will be good!
Upvotes: 3
Reputation: 132
'this' refers to the object that is calling the function, not the calling function. Are you running this code from a browser (i.e. from a web page)? If so, then 'this' is the window that the code is running in.
Upvotes: 0