2013-10-13 150 views
0

我負責一個JavaScript web應用程序。這是非常複雜的,而且我遇到一些麻煩語法:Javascript變量聲明語法

getThemeBaseUrl = function() { 
    var customConfigPath = "./customer-configuration";      
    if (parseQueryString().CustomConfigPath) {       
    customConfigPath = parseQueryString().CustomConfigPath; 
    } 
    var clientId = parseQueryString().ClientId; 

    return customConfigPath + "/themes/" + clientId; 
}; 

parseQueryString = function() { 
    var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m; 
    while (m = re.exec(queryString)) { 
    result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); 
    } 
    return result; 
}; 
特別 parseQueryString().CustomConfigPath

var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;

第一似乎是一種由parseQueryString功能屬性訪問。

第二個看起來是數組聲明,但沒有Array()構造函數。此外,m值在while循環中沒有推測的數組結果時被調用。

回答

0

通過觀察:

parseQueryString().CustomConfigPath 

可以說parseQueryString()有望與CustomConfigPath屬性返回一個對象。

而從這個:

var result = {}; 

你看到result確實是一個對象({}是一個空對象文本)。 這不是一個數組。後來,在一個循環中,有:

result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); 

,所以我們要指定屬性的result對象。其中一個屬性將會(正如我們所預料的)一個CustomConfigPath。這將取自查詢字符串 - 我們將使用正則表達式來執行此操作:re = /([^&=]+)=([^&]*)/g。因此,執行此代碼的網頁的地址如下所示:http://example.com/something?SomeKey=value&CustomConfigPath=something

爲一個對象指定屬性一般語法是:

result[key] = value; 
// key -> decodeURIComponent(m[1]) 
// value -> decodeURIComponent(m[2]) 
0

parseQueryString().CustomConfigPath調用parseQueryString函數返回一個對象。然後它訪問該對象的CustomConfigPath屬性。對於前4行的函數的一個常見的成語是:

var customConfigPath = parseQueryString().CustomConfigPath || "/.customer-configuration"; 

var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m是4個不同的變量的聲明,而不是一個陣列:

  • result是一個空對象
  • queryString是來自當前URL的查詢字符串,其中?已被刪除。
  • re是正則表達式
  • m是未初始化的變量,它將在後面在while循環分配。