Reputation: 23634
obj = {
go: function() { alert(this) }
}
obj.go(); // object
(obj.go)(); // object
(a = obj.go)(); // window
(0 || obj.go)(); // window
Can anyone explain me why the latter two prints window object and the first two prints the reference.
Upvotes: 3
Views: 80
Reputation: 707148
When you execute a method directly, like the last two forms do, the this
pointer is not set to the object. When not in strict mode, it is set to window
(in strict mode, it would be set to undefined which helps you catch errors). The this
pointer is set according to how you call something in javascript.
The simplest way to always make sure the this
pointer is set accordingly is to always call the method in the context of an object like:
obj.go();
Here are some examples:
obj.method() // this in method automatically set to obj
var a = obj.method();
a(); // this set to window as no object context is provided
var a = obj.method();
a.call(obj) // this explicitly set to obj by .call()
a.apply(obj) // this explicitly set to obj by .apply()
What you should remember is that obj.go
is just a function in javascript that was originally stored as a property on obj
. But, once you've gotten that property value, it is just a function pointer and no longer has any explicit association to any particular object. You have to give it an association to an object in how you call it if you want the this
pointer set appropriately inside the method. This is different than in some other languages and like many things in JS that are different, it can be both a feature you can take advantage of and occasionally confusing to learn.
Upvotes: 6