instanceof jQueryjQuery 物件本質上是 jQuery.fn.init 的實例,原型鏈上掛載在 jQuery.prototype(即 jQuery.fn)。因此:
var $div = $('div');
console.log($div instanceof jQuery); // true
var nativeDiv = document.getElementById('test');
console.log(nativeDiv instanceof jQuery); // false
// 關鍵:在 .each() 回呼中,this 是原生 DOM 元素
$('.items').each(function() {
console.log(this instanceof jQuery); // false (原生 Element)
console.log($(this) instanceof jQuery); // true (包裝後)
});
typeof 或 .constructor?typeof $div === 'object':無法區分 jQuery 物件與普通物件/陣列/DOM 元素。$div.constructor === jQuery:跨 iframe/frame 時構造函數引用不同,會誤判;且可被竄改。$.isArray($div) / Array.isArray($div):jQuery 物件是類陣列但非陣列,回傳 false。若需支援 Zepto、jQuery Slim、或自訂類陣列物件,可檢測關鍵特徵:
function isjQueryLike(obj) {
return obj &&
typeof obj === 'object' &&
typeof obj.length === 'number' &&
typeof obj.jquery === 'string' && // jQuery 專有版本號屬性
typeof obj.eq === 'function' && // 核心方法存在
typeof obj.get === 'function';
}
// 測試
console.log(isjQueryLike($('div'))); // true
console.log(isjQueryLike($('.items'))); // true
console.log(isjQueryLike(document.body)); // false
console.log(isjQueryLike({ length: 0, jquery: '3.6.0', eq: function(){}, get: function(){} })); // true (鴨子類型)
function isJQuery(obj: any): obj is JQuery {
return obj instanceof JQuery; // 需 @types/jquery
}
// 使用
function handle(el: JQuery | HTMLElement) {
if (isJQuery(el)) {
el.fadeIn(); // 類型縮窄為 JQuery
} else {
el.style.display = 'block'; // 類型縮窄為 HTMLElement
}
}
$(el) 正規化。console.log(isjQueryLike(obj) ? 'jQuery物件' : '其他')。expect(result).toBeInstanceOf(jQuery) (Jest)。