2009-01-28 102 views

回答

20

取決於jQuery的內部工作,但我會用

obj instanceof jQuery 

這是最走 'JavaScript的方式'做到這一點。請記住,在窗口/框架邊界之間傳遞對象時它會失敗!

託默勒格的建議

'jquery' in obj 

還是應該在這種情況下工作,所以你如果你希望做的多窗口的數據交換應該使用它。我不會推薦它作爲一個通用的解決方案,因爲只是尋找一個名爲'jquery'的屬性不是很可靠。

如果obj是原語,in運算符也會拋出錯誤。如果這種行爲是不需要的,你可以考慮使用這些測試,而不是一個:

obj && obj.jquery 
'jquery' in Object(obj) 

我找到第二個更具吸引力,但第一個將有可能更快。

檢查

Object(obj).hasOwnProperty('jquery') 

會失敗,因爲jQuery的對象只能繼承其原型屬性。

我也打消了使用constructor屬性在JavaScript類型檢查 - 這可能可靠地工作jQuery的,但作爲constructor只是對象的屬性由構造函數的prototype屬性在實例化時指出,有很多方法與測試等亂七八糟......


補充說明:

jQuery的本身檢查obj && obj.jquery。它不會使用instanceof甚至一次。相反,它使用組合typeof,duck-typing和toString.call()進行類型檢查,這應該在instanceof將失敗的情況下運行。另外,hasOwnProperty()也不會被使用。我不確定這是什麼說的關於jQuery庫的代碼質量;)

+1

比我的文章更詳細:+1和我推薦你的文章被選爲答案 – VonC 2009-01-28 11:36:28

6

下列之一:

obj instanceof jQuery 
obj && obj.constructor == jQuery 
obj && obj.jquery 

的instanceof is recommended

+0

what about:「jquery」in obj? – Tomalak 2009-01-28 08:59:10

+0

我建議不要使用instanceof,因爲在IE中使用instanceof時[已知內存泄漏](http://ajaxian.com/archives/working-aroung-the-instanceof-memory-leak)。 – kflorence 2011-02-21 20:59:59

0

用這個而不是instanceof來測試jQuery對象。

/** 
* @see http://ajaxian.com/archives/working-aroung-the-instanceof-memory-leak 
* @return Boolean True if object is of type jQuery, false otherwise 
*/ 
function isjQuery(obj) { 
    return obj && obj.hasOwnProperty && obj instanceof jQuery; 
} 
相關問題