The issue lies with the this
keyword and what it refers to:
foo: function(){
console.log(this.prop);
(function bar(){
console.log(this.prop); <--- in this context, 'this' refers to the window object
})();
}
To solve this, you need to store a reference to the outer this
:
foo: function(){
console.log(this.prop);
var that = this;
(function bar(){
console.log(that.prop); <--- problem solved!
})();
}
Explanation
The confusion arises from how JavaScript determines the context when a function is invoked.
function Test() {
this.name = "Test";
this.bar = function() { console.log("My name is: "+ this.name);}
}
function Blub() {
this.name = "Blub";
this.foo = function() { console.log("My name is: " + this.name);}
}
var a = new Test();
var b = new Blub();
// expected behavior
a.bar(); // My name is: Test
b.foo(); // My name is: Blub
// let's have some fun
a.foo = b.foo; // guess what will happen...
a.foo() // My name is: Test
Wait, why are we still referencing the method
of Test? It's actually pointing to the unbound function
of Blub.
JavaScript determines the value of this
based on the use of .
(dots).
When invoking an anonymous function without an object reference (no dot), it defaults this
to the global object - which is typically the window object in browsers.
Here's another example where things go awry:
var str = "Hello World";
var ord = str.charCodeAt; // shortcut... but not a good one
ord(0) // no dot...
Rather than getting char codes from str
, we end up with those from the global object, resulting in "[object DOMWindow]"
.