2013-04-08 27 views
0

我寫了一個名爲global.js JavaScript文件具有以下內容:對象沒有定義或空

; 

var Globals = 
{ 
    function getAppRoot() { 
     if (typeof (jQuery) !== "undefined") 
      return $("#ApplicationRoot").attr("href"); 
    }; 

    appRoot : getAppRoot(); 
}; 
在我的HTML文件(ASP.NET MVC項目)

然後,我包括我的JavaScript文件,像這樣:

<link rel = "home" id = "ApplicationRoot" 
    href = "@Url.Content("~/")" /> 

<script src = "@Url.Content("~/Scripts/jquery-1.8.3.js")" 
    type="text/javascript"></script> 

<script src = "@Url.Content("~/Scripts/global.js")" 
    type = "text/javascript"></script> 

,然後在HTML文件,一個腳本標籤中,我寫的:

$(document).ready( 
    function() { 
     alert("Globals.appRoot = " + window.Globals.appRoot); 
    }); 

然而,當I R un代碼,它告訴我Globals是未定義的。

UPDATE 謝謝大家。我只注意到我忘記了等號(賦值運算符)。

,我現在看到(我還沒有完全確定的)另一個重要的事情是:我從您的意見假設一個對象的聲明如下所示:

var foo = { /* cannot have anything that does not adhere to the bar : gar syntax? */ } 

另一個更新 事情是:

var Globals = 
{ 
    appRoot : function() { } 
}; 

或像這樣:

,如果我這樣做取得 appRoot的方法

客戶必須使用以下一組括號調用appRoot。我想appRoot是一個屬性,而不是一個方法。我怎麼做?

最後更新 我現在已經改變了我的代碼如下:

// globals.js 
// I understand that the starting semi-colon is not 
// required. I'd left it in for reasons that it is used 
var Globals = 
{ 
    appRoot : $("#ApplicationRoot").attr("href"); 
}; 


// inside the HTML file in $(document).ready(); 

if (tyepof(Globals) == "undefined" || Globals == null) 
    alert("Globals is either undefined or null"); 
else 
    alert("Globals.appRoot = " + Globals.appRoot); 

我得到的警告消息全局要麼是未定義或爲空

ANSWER 好的,最後。感謝你的幫助。我在Globals對象的對象聲明/初始化中遇到了另一個小的語法錯誤。

由於appRoot是該對象的成員,並且我使用的是對象初始化程序的語法,所以我不應該用分號終止appRoot的聲明。相反,我應該使用逗號,或者只是將它留下而沒有任何終止字符,因爲它是最後一個(也是Globals的唯一成員)。

+2

看上去真的像JavaScript。 – 2013-04-08 14:06:22

+4

代碼中有幾個語法錯誤。如果您在瀏覽器中查看JavaScript控制檯(如果您沒有,請使用更現代的瀏覽器:-)),您會看到各種消息指出錯誤。 *編輯:即使是剛纔的編輯。* – 2013-04-08 14:07:19

+0

*「'var foo = {/ *不能有任何不符合bar:gar語法?* /}'」*正確。它被稱爲*對象初始值設定項*(有時是「對象字面量」),詳見[規範](http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5)。 – 2013-04-08 14:16:42

回答

2

global.js應該看起來更像是這樣的:

//; << not needed 
var Globals = /*equal to missing*/ 
{ 
    appRoot : function getAppRoot() { 
     if (typeof (jQuery) !== "undefined") 
      return $("#ApplicationRoot").attr("href"); 
    } 
}; 
3

你需要重新寫你的globals.js,這樣的事情應該工作:

var Globals = { 
    appRoot : function() { 
     if (typeof (jQuery) !== "undefined") { 
      return $("#ApplicationRoot").attr("href"); 
     } 
    } 
}; 
相關問題