你的問題是this
和它所引用:
foo: function(){
console.log(this.prop);
(function bar(){
console.log(this.prop); <--- this does not reference to foo here, but instead it refers to the window object
})();
}
你需要保持到外this
參考:
foo: function(){
console.log(this.prop);
var that = this;
(function bar(){
console.log(that.prop); <--- tada!
})();
}
更新
一些解釋。這都是關於JavaScript在調用函數時如何確定上下文的。
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();
// this works as expected
a.bar(); // My name is: Test
b.foo(); // My name is: Blub
// let's do something fun
a.foo = b.foo; // make an educated guess what that does...
a.foo() // My name is: Test
咦?我們是不是參考Blub的method
?沒有,我們沒有。我們引用Blub的未綁定function
。
JavaScript綁定到.
(點),並基於它決定值this
應該是。
既然你沒有在一個對象上調用你的匿名函數(因此沒有.
),它將使得this
引用全局對象,在瀏覽器的情況下,它是窗口對象。
又如(有人可能認爲這會工作):
var str = "Hello World";
var ord = str.charCodeAt; // let's make a little shortcut here.... bad idea
ord(0) // no dot...
取而代之的是在str
我們得到的是在全局對象的那些炭代碼,當然這不是一個字符串,因此charCodeAt
撥打電話toString
其結果爲"[object DOMWindow]"
+1爲第一個解決方案! – 2010-11-23 22:17:49