2013-10-03 62 views
0

我正在學習udacity的課程並遇到問題。「this」如何影響方法的方法?

https://www.udacity.com/course/viewer#!/c-cs255/l-49464373/e-73862317/m-73162952

function xhrGet(reqUri,callback) { 
    var xhr = new XMLHttpRequest(); 

    xhr.open("GET", reqUri, true); 
    xhr.onload = callback; 

    xhr.send(); 
} 

var TILEDMapClass = Class.extend({ 

    // Boolean flag we set once our map atlas 
    // has finished loading. 
    fullyLoaded: false, 

    //----------------------------------------- 
    // Load the json file at the url 'map' into 
    // memory. This is similar to the requests 
    // we've done in the past using 
    // XMLHttpRequests. 
    load: function (map) { 

     // Perform an XMLHttpRequest to grab the 
     // JSON file at url 'map'. We've provided 
     // the xhrGet function from the optional 
     // unit for you to use if you want. 
     // 
     // Once the XMLHttpRequest loads, set the 
     // 'fullyLoaded' flag to true. 
     // 
     // YOUR CODE HERE 
     xhrGet(map, function(){ 
      this.fullyLoaded = true; 
     }); 
    } 

}); 

// We define a single global instance of our 
// map for the rest of our game code to access. 
var gMap = new TILEDMapClass(); 

鏈接說,它使用gMap.load.apply(gMap, [jsonURL]); http://forums.udacity.com/questions/100058023/scope-of-this#cs255

,但我認爲inspite其實使用被叫評判。(負載將屬於GMAP)

但因爲

xhr.onload = function(){ 
       this.fullyLoaded = true; 
      } 

是一種方法屬於XHR對象,

this是匿名函數

this內部應引用XHR不GMAP。

爲什麼this引用gMap?

回答

1

this並不一定意味着該功能或對象它被稱爲上,如果你習慣使用jQuery和這個都搞不清楚,jQuery的方法實際上是通過調用一個設置它的所有功能爲方便this其中設置this給調用者這兩個函數:

call(object, arg0, arg1...); 
apply(object, args[]); 

因此,基本上,除非函數是通過調用上述功能中的一個設置this,其將被設置爲一些外功能/對象或window

+0

不錯,簡潔 – mlnyc

2

這個在關閉時很有趣。你必須記住,這個關鍵字通常指的是方法的所有者。通常是調用者(全局函數的窗口),但是當方法被調用爲對象的屬性時,這將引用對象本身。

請參閱:「如果該函數被調用爲父項的屬性,則此參考函數代碼中的父對象」。 Understanding this

將直接從Understanding this規則:

  • 默認情況下,這指的是全局對象。
  • 當函數被調用爲父對象的屬性時,此 引用該函數內的父對象。
  • 使用new運算符調用某個函數時,這指的是該函數內新創建的對象。
  • 當使用call或apply調用某個函數時,這指的是傳遞給call或apply的第一個參數 。如果第一個參數爲空 或者不是對象,則它指向全局對象。
+0

但執行應該由xhr.load()調用?那爲什麼這不是指向xhr? –

+0

當使用call或apply調用某個函數時,這指的是傳遞給call或apply的第一個參數。如果第一個參數爲null或不是對象,則它指向全局對象。在這種情況下,gMap.load.apply(gMap,[jsonURL]);將gMap作爲第一個對象。它變得棘手,但適用於這個原因 – mlnyc

1

「本」在JavaScript函數無關,其功能屬於的對象,但什麼對象是執行

對比與Java,其中那些是相同的因爲一個方法真的是一個對象的一部分,沒有一個方法就不能存在(不考慮靜態)。

例如:

var blah = { 
    test: function() { 
    console.log('test'); 
    } 
}; 
var f = blah.test; 
var bleh = { 
    test: blah.test 
} 

如果我再使這三個函數調用的,什麼是「本」,在指向每個調用?

blah.test(); // this points to blah 
f();   // this is null (or undefined, not sure which) 
bleh.test(); // this is bleh 

我還可以使用Function.call調用一個函數對象中的任何對象的情況下:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

f.call(window); // this is window 

瞭解與回調工作時,因爲回調函數通常是「本」難由一些其他庫(例如jquery)調用,它們的API可能會或可能不會保證「this」是指什麼。你能做些什麼,作爲一個變通:

someAsyncFunction(function() { 
    bleh.test(); 
}); 

這將確保你所關心的是帶一個可預見的「此」參考值的功能。

相關問題