>  기사  >  웹 프론트엔드  >  jQuery를 확장()에 대한 자세한 설명

jQuery를 확장()에 대한 자세한 설명

小云云
小云云원래의
2018-01-12 11:18:141234검색

이 글은 주로 jQuery 확장()에 대한 자세한 설명과 간단한 예제를 소개합니다. 필요한 친구들이 참고하면 도움이 될 것입니다.

jQuery 확장() 자세한 설명과 간단한 예제

jQuery를 사용해보면 jQuery의 일부 함수가 다음과 같이 사용되는 것을 볼 수 있습니다.


$.get(); 
$.post(); 
$.getJSON();

일부 함수는 다음과 같이 사용됩니다.


$('p').css(); 
$('ul').find('li');

일부 함수는 다음과 같이 사용됩니다.


$('li').each(callback); 
$.each(lis,callback);

여기에는 도구 메서드와 인스턴스 메서드라는 두 가지 개념이 관련됩니다. 일반적으로 우리가 말하는 도구 메서드는 첫 번째 코드 조각과 같이 인스턴스화 없이 호출할 수 있는 함수를 참조하며, 인스턴스 메서드는 두 번째 코드 조각과 같이 개체가 인스턴스화된 후에만 호출할 수 있는 함수를 의미합니다. jQuery의 많은 메서드는 인스턴스 메서드이자 도구 메서드이지만 호출 메서드는 세 번째 코드와 같이 약간 다릅니다. JavaScript의 도구 메소드와 인스턴스 메소드를 보다 명확하게 설명하기 위해 다음과 같은 테스트를 수행합니다.


functionA(){ 
     
  } 
  A.prototype.fun_p=function(){console.log("prototpye");}; 
  A.fun_c=function(){console.log("constructor");}; 
  var a=new A(); 
  A.fun_p();//A.fun_p is not a function 
  A.fun_c();//constructor 
  a.fun_p();//prototpye 
  a.fun_c();//a.fun_c is not a function

위의 테스트를 통해 인스턴스 메소드가 프로토타입에 정의되어 있고 도구 메소드가 생성자에 직접 추가되었다는 결론을 내릴 수 있습니다. 인스턴스 메소드는 생성자가 호출할 수 없습니다. 도구 메서드는 인스턴스에서 호출할 수 없습니다.

물론 인스턴스 메서드는 프로토타입에서만 정의할 수 있는 것이 아니라 다음과 같은 세 가지 정의 메서드가 있습니다.


functionA(){ 
    this.fun_f=function(){ 
        console.log("Iam in the constructor"); 
    }; 
} 
A.prototype.fun_p=function(){ 
    console.log("Iam in the prototype"); 
}; 
var a=newA(); 
a.fun_f();//Iam in the constructor 
a.fun_i=function(){ 
    console.log("Iam in the instance"); 
}; 
a.fun_i();//Iam in the instance 
a.fun_p();//Iam in the prototype

이 세 가지 메서드의 우선순위는 다음과 같습니다. 인스턴스에 직접 정의된 변수는 인스턴스보다 우선순위가 더 높습니다. 정의 "this"에 대해 정의된 변수와 "this"에 정의된 변수는 프로토타입에 의해 정의된 변수보다 높습니다. 즉, 인스턴스에 직접 정의된 변수는 "this"와 프로토타입에 정의된 변수를 덮어쓰고, "this"에 정의된 변수는 프로토타입에 정의된 변수를 덮어씁니다.

아래 jQuery의 extend() 메소드 소스코드를 살펴보세요.


jQuery.extend = jQuery.fn.extend = function() { 
    var options,name, src, copy, copyIsArray, clone, 
        target= arguments[0] || {}, 
        i =1, 
        length= arguments.length, 
        deep= false; 
    // Handle adeep copy situation 
    if ( typeoftarget === "boolean" ) { 
        deep= target; 
        //Skip the boolean and the target 
        target= arguments[ i ] || {}; 
        i++; 
    } 
    // Handlecase when target is a string or something (possible in deep copy) 
    if ( typeoftarget !== "object" && !jQuery.isFunction(target) ) { 
        target= {}; 
    } 
    // ExtendjQuery itself if only one argument is passed 
    if ( i ===length ) { 
        target= this; 
        i--; 
    } 
    for ( ; i< length; i++ ) { 
        //Only deal with non-null/undefined values 
        if ((options = arguments[ i ]) != null ) { 
            //Extend the base object 
            for( name in options ) { 
                src= target[ name ]; 
                copy= options[ name ]; 
                //Prevent never-ending loop 
                if( target === copy ) { 
                   continue; 
                } 
                //Recurse if we&#39;re merging plain objects or arrays 
                if( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray= jQuery.isArray(copy)) ) ) { 
                   if( copyIsArray ) { 
                       copyIsArray= false; 
                       clone= src && jQuery.isArray(src) ? src : []; 
                   }else { 
                       clone= src && jQuery.isPlainObject(src) ? src : {}; 
                   } 
                   //Never move original objects, clone them 
                   target[name ] = jQuery.extend( deep, clone, copy ); 
                //Don&#39;t bring in undefined values 
                }else if ( copy !== undefined ) { 
                   target[name ] = copy; 
                } 
            } 
        } 
    } 
    // Returnthe modified object 
    return target; 
};

(1) 우선 jQuery의 extend() 메소드 구현과 프로토타입은 동일한 함수를 사용합니다.

(2) Extension()에 매개변수가 하나만 있는 경우 jQuery 객체에 플러그인이 추가됩니다. jQuery에서 확장된 것을 도구 메소드라고 하며, jQuery.fn(jQuery 프로토타입)에서 확장된 것은 인스턴스 메소드입니다. jQuery와 프로토타입에서 동일한 이름의 함수를 확장하더라도 jQuery 객체를 사용하면 호출됩니다. 도구 메서드를 사용합니다. jQuery() 인스턴스 메서드가 호출됩니다.

(3) Extension()에 여러 매개변수가 있는 경우 다음 매개변수는 첫 번째 매개변수로 확장됩니다.


var a={}; 
$.extend(a,{name:"hello"},{age:10}); 
console.log(a);//Object{name: "hello", age: 10}

(4) 얕은 복사본(기본값):


var a={}; 
varb={name:"hello"}; 
$.extend(a,b); 
console.log(a);//Object{name: "hello"} 
a.name="hi"; 
console.log(b);//Object{name: "hello"}

b는 a의 영향을 받지 않지만 b의 속성 중 하나가 객체인 경우:


var a={}; 
varb={name:{age:10}}; 
$.extend(a,b); 
console.log(a.name);//Object{age: 10} 
a.name.age=20; 
console.log(b.name);//Object{age: 20}

Due 얕은 복사본으로 완료할 수 없으면 b.name은 a의 영향을 받게 됩니다. 이때 우리는 종종 깊은 복사본을 만들고 싶어합니다.

딥 카피:


var a={}; 
varb={name:{age:10}}; 
$.extend(true,a,b); 
console.log(a.name);//Object{age: 10} 
a.name.age=20; 
console.log(b.name);//Object{age: 10}

b.name은 a의 영향을 받지 않습니다. ㅋㅋㅋ
jQuery_jquery

에서 $.extend() 사용 예

위 내용은 jQuery를 확장()에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.