I can't seem to get my head around a specific case of scoping for JavaScript variables. Different from other examples and questions I have found, I am interested in the scoping for nested functions.
I've set up an example at this JSFiddle. The relevant part is the following:
function MyObject() {
var self = this;
var a = 1;
this.b = 2;
var innerMethod = function() {
//1 and 2: direct reference
logMessage("a = " + a); // a = 1
//logMessage("b = " + b); // Error: b is not defined
//3 and 4: using this
logMessage("this.a = " + this.a); // this.a = undefined
logMessage("this.b = " + this.b); // this.b = undefined
//5 and 6: using self
logMessage("self.a = " + self.a); // self.a = undefined
logMessage("self.b = " + self.b); // self.b = 2
}
}
Now, I understand that a reference to a
directly works.
I also understand that messages 3 and 4 (this.a
and this.b
) will fail because this
refers to the internal function. I also understand that line 6 works because I save the reference to the original object.
What I do not understand is:
- why aren't messages 1 and 2 working alike?
- why aren't messages 5 and 6 working alike?
this
namespace is implicit, which is not the case for JS. – Emmittemmonsvar a = 5;
) with things that are not variables but properties of objects (this.b = 10;
sets the propertyb
of the object thatthis
refers to to10
). These things are not the same and therefore do not behave identically. – BaroninnerMethod.call(this);
orthis.method = innerMethod;
and(new MyObject()).method();
– Marinatethis
reference is a little out of the scope of the question I believe, but here's a good article if OP or anyone wants to read: Mythical methods by TJ Crowder. – Emmittemmons