2012-05-02 28 views
2

我已經開始使用JavaScript和jQuery進行試驗。我試圖創建一個類,將加載到指定的div的json文件,但我遇到了一個行爲,我不明白:的JavaScript jquery.getJSON怪異的行爲

注:我知道這段代碼不會加載任何東西到一個div,這只是我能找到展現我不理解的行爲最短的例子。

function test(div) { 
    this.div = div; 
    _this = this; 
    jQuery.getJSON('/example.json', null, function(data) { 
     console.log(_this.div); 
    }); 
} 

當我運行

a = new test("a"); 
b = new test("b"); 

我期望看到 「AB」 作爲輸出,但實際產量是 「BB」。 但是,如果我允許第一線調用第二個之前完成,則預期輸出被示出。我很困惑!

回答

5

_this是一個全局變量,之前添加var

工作例如:http://jsfiddle.net/SQRwn/

順便問一下,你的代碼將正常工作,如果它是下面的,但你必須在這裏是什麼可能不是你要使用的代碼...

function test(div) { 
    jQuery.getJSON('/example.json', null, function(data) { 
     console.log(div); 
    }); 
} 
2

如果不包括var您的變量之前,它成爲一個全局變量:

_this = this; 

shoudl是

var _this = this; 
1

這是因爲您沒有妥善保護_this變量,它是全球性的。更改行這樣:

var _this = this; 

與您的代碼示例,但是,你甚至都不需要緩存this

function test(div) { 
    jQuery.getJSON('/example.json', null, function(data) { 
     console.log(div); 
    }); 
}