program tip

객체가 jQuery 객체인지 확인

radiobox 2020. 10. 3. 10:24
반응형

객체가 jQuery 객체인지 확인


객체가 jQuery 객체인지 네이티브 JavaScript 객체인지 확인하는 빠른 방법이 있습니까?

예:

var o = {};
var e = $('#element');

function doStuff(o) {
    if (o.selector) {
        console.log('object is jQuery');
    }
}

doStuff(o);
doStuff(e);

분명히 위의 코드는 작동하지만 안전하지 않습니다. 잠재적으로 o개체에 선택기 키를 추가 하고 동일한 결과를 얻을 수 있습니다. 객체가 실제로 jQuery 객체인지 확인하는 더 좋은 방법이 있습니까?

일치하는 것 (typeof obj == 'jquery')


instanceof연산자 를 사용할 수 있습니다 .

obj instanceof jQuery

설명 : jQuery함수 (일명 $)는 생성자 함수 로 구현됩니다 . 생성자 함수는 new접두사 와 함께 호출됩니다 .

호출 할 때 $(foo)내부적으로 jQuery는 이것을 new jQuery(foo)1로 변환합니다 . JavaScript this는 생성자 함수 내에서 초기화를 진행하여 의 새 인스턴스를 가리키고 jQuery속성을 jQuery.prototype(일명 jQuery.fn) 에서 찾은 속성으로 설정합니다 . 따라서, 당신은 얻을 new목적 instanceof jQuery입니다 true.


1 실제로 new jQuery.prototype.init(foo): 생성자 논리가라는 다른 생성자 함수로 오프로드 init되었지만 개념은 동일합니다.


http://api.jquery.com/jquery-2/에 설명 된대로 .jquery 속성을 사용할 수도 있습니다.

var a = { what: "A regular JS object" },
b = $('body');

if ( a.jquery ) { // falsy, since it's undefined
    alert(' a is a jQuery object! ');    
}

if ( b.jquery ) { // truthy, since it's a string
    alert(' b is a jQuery object! ');
}

instanceof 연산자를 확인하십시오 .

var isJqueryObject = obj instanceof jQuery

객체의 인스턴스를 확인하는 가장 좋은 방법은 instanceof 연산자를 사용 하거나 객체의 프로토 타입이 다른 객체의 프로토 타입 체인에 있는지 검사하는 isPrototypeOf () 메서드 를 사용하는 것입니다.

obj instanceof jQuery;
jQuery.prototype.isPrototypeOf(obj);

그러나 문서에 여러 jQuery 인스턴스가있는 경우 실패 할 수 있습니다. @Georgiy Ivankin이 언급했듯이 :

만약 내가 $내 현재 이름 공간 가리키는 jQuery2내가 외부 네임 스페이스 (어디에서 개체를 가지고 $있다 jQuery1) 그때 사용할 수있는 방법이 없다 instanceof그 객체가있는 경우 확인하기 위해이 jQuery객체가

이 문제를 극복하는 한 가지 방법은 클로저 또는 IIFE 에서 jQuery 객체의 별칭을 지정하는 것입니다.

//aliases jQuery as $
(function($, undefined) {
    /*... your code */

    console.log(obj instanceof $);
    console.log($.prototype.isPrototypeOf(obj));

    /*... your code */
}(jQuery1));
//imports jQuery1

이 문제를 극복하는 다른 방법 jqueryobj

'jquery' in obj

However, if you try to perform that checking with primitive values, it will throw an error, so you can modify the previous checking by ensuring obj to be an Object

'jquery' in Object(obj)

Although the previous way is not the safest (you can create the 'jquery' property in an object), we can improve the validation by working with both approaches:

if (obj instanceof jQuery || 'jquery' in Object(obj)) { }

The problem here is that any object can define a property jquery as own, so a better approach would be to ask in the prototype, and ensure that the object is not null or undefined

if (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery)) { }

Due to coercion, the if statement will make short circuit by evaluating the && operator when obj is any of the falsy values (null, undefined, false, 0, ""), and then proceeds to perform the other validations.

Finally we can write an utility function:

function isjQuery(obj) {
  return (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery));
}

Let's take a look at: Logical Operators and truthy / falsy


return el instanceof jQuery ? el.size() > 0 : (el && el.tagName);

However, There is one more way to check the object in jQuery.

jQuery.type(a); //this returns type of variable.

I have made example to understand things, jsfiddle link


For those who want to know if an object is a jQuery object without having jQuery installed, the following snippet should do the work :

function isJQuery(obj) {
  // Each jquery object has a "jquery" attribute that contains the version of the lib.
  return typeof obj === "object" && obj && obj["jquery"];
}

You can check if the object is produced by JQuery with the jquery property:

myObject.jquery // 3.3.1

=> return the number of the JQuery version if the object produced by JQuery. => otherwise, it returns undefined


var elArray = [];
var elObjeto = {};

elArray.constructor == Array //TRUE
elArray.constructor == Object//TALSE

elObjeto.constructor == Array//FALSE
elObjeto.constructor == Object//TRUE

참고URL : https://stackoverflow.com/questions/1853223/check-if-object-is-a-jquery-object

반응형