When you try and access a variable, JavaScript, first look for that variable in the current function scope, next, in the enclosed functions scope and then finally in the global scope. In your case, self
is a member of this
, global object. When you say this.self
, and if this
refers to the global scope, this.self
is same as the self
. Unless you change the current context, this
will refer to the global object and it should work. Check the following example to understand better.
myGlobalVar = function() {
this.self = "thefourtheye";
this.Whatever = function() {
console.log(self);
console.log(this.self);
console.log(this.self === self);
}
}
var b = {
self: "thethirdeye"
}
myGlobalVar();
Whatever();
console.log("-------------------");
Whatever.apply(b);
Output
thefourtheye
thefourtheye
true
-------------------
thefourtheye
thethirdeye
false
When I am calling Whatever
, the second time, I am setting the current context to object b
, with apply. So, now this
points to b
. Now, self
is different from this.self
. When I refer self
, it looks up the hierarchy and finds self
in the global scope, it prints thefourtheye
, when I say this.self
, it looks up self
in b
and it prints thethirdeye
. Hope its clear now.