2014-08-31 28 views
-3

我想創建一個函數,循環遍歷所有對象,以便在理解JavaScript代碼時找到與此關鍵字匹配的內容?如何通過全局和子對象循環查找在JavaScript中與此關鍵字匹配?

開始了這樣的:

function valueOfTHis (this) { 

    for(var thisObject in window) { 
     if(thisObject === "object" && this === "thisObject") {  
      console.log("match found for this keyword: "+ thisObject); 
     }          
    } 
} 

如何檢查窗口對象的子子子對象針對此關鍵字的匹配?

+3

無論你認爲你使用這段代碼做什麼,都要停下來。這是不對的。 – Adam 2014-08-31 23:16:01

+0

你在問什麼?我無法理解你的問題。 – 2014-08-31 23:16:06

+0

我認爲他們想要通過'window'對象上的字符串進行屬性名的遞歸搜索? – 2014-08-31 23:22:38

回答

0

在您的代碼:

function(this) { 

如果關鍵字功能出現在一份聲明中的第一個標記,它代表了一個函數聲明的開始和必須遵循的一個有效標識符是函數名字,所以:

function myFunc(...) { 

你不能在參數列表使用這個,這是一個keyword這使得它reserved word而不是VA蓋子標識符。如果你正在尋找在標識符傳遞和尋找它在窗口上(全局)對象和子對象,那麼你可以嘗試:

function myFunc(name) { 

    // If not set by the call, this will be the global object (window in a browser) 
    // but will remain undefined in strict mode 
    var thisObj = this; 

    // For every enumerable property of thisObj 
    for (var key in thisObj) { 

     // Does name match property name? 
     if (name == key) { 
      console.log('Match found for ' + name + ': ' + thisObj[key]); 
     } 

     // If property is an object, search it too 
     // Set this to the object in the call 
     if (typeof thisObj[key] == 'object') { 
      console.log(thisObj[key]); 

       // Recursively call the function. This may take a very long time, 
       // uncomment at your own risk 
       // myFunc.call(thisObj[key], name); 
     } 

    } 
} 

myFunc('alert'); 

這將找到匹配enmuerable性質被叫全局對象,它是子對象。在嚴格模式下,你將需要調用它像:

myFunc.call(this, name); 

確保在第一次調用正確設置。

+0

非常感謝Rob爲了解我的問題提供了足夠的解決方法 – 2014-09-01 01:35:55

+0

感謝您的學習時刻,我不知道這個關鍵字不能作爲函數的參數使用,而且它是不可能的 – 2014-09-01 01:44:00