2009年5月8日 星期五

[jquery]typeof的使用

JQuery的前面幾句就把我給搞得暈了頭,只能對其中的一點一滴去測試。第一句:
if (typeof window.jQuery == "undefined")

typeof的語法是:typeof[(]expression[)]
即typeof後面跟一個表達式,要不要括號都可以。它將返回一個字符串,表示表達式

的類型,而類型只有六種可能:number、string、boolean、object、function、

undefined
這是typeof返回的類型,與實際的數據類型,以及內部對象還是有區別的。
實際的類型可以參考微軟的一份JScript幫助文檔中的「JScript 的數據類型」,其中

還有null,但null經過typeof返回的類型是object。而一個變量,如果沒有賦值時,

它的類型為undefined,但它值為null。
var x;
alert(typeof(x));
if (x==null) alert("OK");
內部對象比這六個多,其中五個有對應的,它們都在首字母大寫:Number、String、

Boolean、Object、Function。undefined沒有對應對象。

以下把幾種情況都列出來:
n=12.2;
alert("n=12.2:" + typeof n);

n="12.2";
alert("n=\"12.2\":" + typeof n);

n=false;
alert("n=false:" + typeof n);

n=[12, 11, 13];
alert("n=[12, 11, 13]:" + typeof n);
alert("n[1]:" + typeof n[1]);

obj=function (){var i=0; function show() { alert(i); }};
n=new obj();
alert("n=new obj():" + typeof n);

n=function () { alert("OK"); };
alert("n=function () { alert(\"OK\"); }:" + typeof n);

alert("nnnnnn:" + typeof nnnnnn);

alert("null:" + typeof null);

以typeof的誤用有如下兩種情況:
if (x == undefined)
if (typeof(x) == undefined)
正確的應該是
if (typeof(x) == "undefined")

對比這兩句話:
//var x;
if (typeof(x) == "undefined") alert("OK1");
if (x==null) alert("OK2");
有定義語句var x;時,兩句都執行正常。
如果沒有定義語句時,第一句沒問題,第二句就提示'x'未定義

再對比這兩句:
x=null;
if (typeof(x) == "undefined") alert("OK1");
if (x==null) alert("OK2");

因此用typeof來檢測變量是否有定義是最合適不過的了。返回到最原始的問題:
if (typeof window.jQuery == "undefined")
{
var jQuery = ...
...
}
這段代碼加上裡面的程序體,就能夠保證程序體只被執行一次,第二次執行時,

typeof window.jQuery就是"function"了。舉例:有個文件,script引用寫了兩遍
1.htm
<html>
<head>
<script language="javascript" type="text/javascript"

src="D:/inetpub/JQuery/JQ.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript"

src="D:/inetpub/JQuery/JQ.js"></script>
<script>
alert("|" + $.trim(" abc ") + "|");
</script>
</body>
</html>
通過斷點,我們可以看出對於jQuery的構建,只在第一次執行。

不過,我感到可惜的是,如果不同窗口,就要分別執行了。如以下兩個文件:
1.htm
<html>
<head>
<script language="javascript" type="text/javascript"

src="D:/inetpub/JQuery/JQ.js"></script>
</head>
<body>
<a href="2.htm">鏈接到第二個頁面2.htm</a>
<script>
alert("|" + $.trim(" abc ") + "|");
</script>
</body>
</html>

2.htm
<html>
<head>
<script language="javascript" type="text/javascript"

src="D:/inetpub/JQuery/JQ.js"></script>
</head>
<body>
第二頁面
<script>
alert("|" + $.trim(" abc ") + "|");
</script>
</body>
</html>
jQuery的構建體就執行了兩遍。

【下列文章您可能也有興趣】

沒有留言: