問題
XMLHttpRequest inside an object: how to keep the reference to “this”
且看代碼
javascriptmyObject.prototye = { ajax: function() { this.foo = 1; var req = new XMLHttpRequest(); req.open('GET', url, true); req.onreadystatechange = function (aEvt) { if (req.readyState == 4) { if(req.status == 200) { alert(this.foo); // reference to this is lost } } } };
在onreadystatechange
回調中再也引用不到主對象的this
了,當然就沒有辦法獲取this.foo
變量了,有什麼辦法可以在這個回調中繼續引用主對象呢
答案
最簡單的辦法就是將主對象的this
保存到局部變量中,
javascriptmyObject.prototype = { ajax: function (url) { // (url argument missing ?) var instance = this; // <-- store reference to the `this` value this.foo = 1; var req = new XMLHttpRequest(); req.open('GET', url, true); req.onreadystatechange = function (aEvt) { if (req.readyState == 4) { if (req.status == 200) { alert(instance.foo); // <-- use the reference } } }; } };
如果我沒有猜錯的話,myObject
是一個構造函數,現在你這麼直接設置它的原型對象,最好還是將原型對象的constructor
屬性(設置)恢復爲myObject
。
附,在<<JavaScript設計模式>>
看到的譯者注:
/*
*譯者注:定義一個構造函數時,其默認的prototype對象是一個Object 類型的實例,其constructor屬性會被自動設置
*爲該構造函數本身。如果手工將其prototype 設置爲另外一個對象,那麼新對象自然不會具有原對象的constructor值,
*所以需要重新設置其constructor 值。
*/