>  기사  >  웹 프론트엔드  >  jQuery_jquery의 확장 함수 구현 원리에 대한 자세한 설명

jQuery_jquery의 확장 함수 구현 원리에 대한 자세한 설명

WBOY
WBOY원래의
2016-05-16 16:16:051352검색

extend()는 jQuery에서 중요한 함수입니다. 객체를 확장하는 데 사용되며, 이전에 언급한 것처럼 jQuery 플러그인 개발에서도 내부적으로 사용됩니다. 기사 noContribute 메소드는 확장 메소드를 사용하여 확장됩니다.

jQuery의 API 매뉴얼에서 우리는 jQuery jQuery.extend() 및 jQuery.fn.extend() 내에서 비록 동일한 코드를 사용하여 구현되지만 실제로는 jQuery와 jQuery.fn에 탑재된 두 가지 다른 메소드인 확장을 볼 수 있습니다. 그들의 기능은 다릅니다. 확장 공식 API 설명을 살펴보겠습니다:

코드 복사 코드는 다음과 같습니다.
jQuery.extend(): 둘 이상의 객체 내용을 첫 번째 객체로 병합합니다. (두 개 이상의 객체를 첫 번째 객체로 병합합니다.)
jQuery.fn.extend():객체의 내용을 jQuery 프로토타입에 병합하여 새로운 jQuery 인스턴스 메서드를 제공합니다. (새 jQuery 인스턴스 메서드를 확장하려면 객체를 jQuery의 프로토타입 속성에 마운트하세요.)

jQuery에는 정적 메서드와 인스턴스 메서드가 있다는 것을 알고 있으므로 jQuery.extend()와 jQuery.fn.extend()의 첫 번째 차이점은 하나는 정적 메서드를 확장하는 데 사용되고 다른 하나는 인스턴스 메서드를 확장하는 데 사용된다는 것입니다. . 사용법은 다음과 같습니다.

jQuery.extend({
 sayhello:function(){
 console.log("Hello,This is jQuery Library");
 }
})
$.sayhello(); //Hello, This is jQuery Library
jQuery.fn.extend({
 check: function() {
 return this.each(function() {
 this.checked = true;
 });
 },
 uncheck: function() {
 return this.each(function() {
 this.checked = false;
 });
 }
})
$( "input[type='checkbox']" ).check(); //所有的checkbox都会被选择

플러그인을 호출하는 방법에는 두 가지가 있습니다. 하나는 $를 사용하여 직접 호출하는 것이고, 다른 하나는 $()를 사용하여 호출하는 것입니다. 또한 jQuery.extend()는 여러 개체를 매개 변수로 받습니다. 매개변수가 하나만 있는 경우 객체의 속성 메서드가 jQuery에 연결되고, 매개변수가 여러 개 포함된 경우 후속 개체의 속성과 메서드가 첫 번째 개체에 연결됩니다. jQuery 확장 구현 소스 코드:

jQuery.extend = jQuery.fn.extend = function() {
 var options, name, src, copy, copyIsArray, clone,
 target = arguments[0] || {},
 i = 1,
 length = arguments.length,
 deep = false;
 // Handle a deep copy situation
 if ( typeof target === "boolean" ) {
 deep = target;
 target = arguments[1] || {};
 // skip the boolean and the target
 i = 2;
 }
 // Handle case when target is a string or something (possible in deep copy)
 if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
 target = {};
 }
 // extend jQuery itself if only one argument is passed
 if ( length === i ) {
 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'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) &#63; src : [];
  } else {
  clone = src && jQuery.isPlainObject(src) &#63; src : {};
  }
  // Never move original objects, clone them
  target[ name ] = jQuery.extend( deep, clone, copy );
 // Don't bring in undefined values
 } else if ( copy !== undefined ) {
  target[ name ] = copy;
 }
 }
 }
 }
 // Return the modified object
 return target;
};
첫눈에 이해하기 어려울 정도로 큰 코드 더미입니다. 실제로 대부분의 코드는 jQuery.extend()에 여러 매개변수가 있는 경우 객체 병합 및 전체 복사 문제를 구현하는 데 사용됩니다. 함수가 제거되면 확장에는 정적 및 인스턴스 메서드를 확장하는 기능만 있으므로 코드는 다음과 같습니다.

jQuery.extend = jQuery.fn.extend = function(obj){
 //obj是传递过来扩展到this上的对象
 var target=this;
 for (var name in obj){
 //name为对象属性
 //copy为属性值
 copy=obj[name];
 //防止循环调用
 if(target === copy) continue;
 //防止附加未定义值
 if(typeof copy === 'undefined') continue;
 //赋值
 target[name]=copy;
 }
 return target;
}

확장 방법에 대해 설명하고 설명하겠습니다.

jQuery.extend = jQuery.fn.extend = function() {
 // 定义默认参数和变量
 // 对象分为扩展对象和被扩展的对象 
 //options 代表扩展的对象中的方法
 //name 代表扩展对象的方法名
 //i 为扩展对象参数起始值
 //deep 默认为浅复制
 var options, name, src, copy, copyIsArray, clone,
 target = arguments[0] || {},
 i = 1,
 length = arguments.length,
 deep = false;
 //当第一个参数为布尔类型是,次参数定义是否为深拷贝
 //对接下来的参数进行处理
 if ( typeof target === "boolean" ) {
 deep = target;
 target = arguments[1] || {};
 // 当定义是否深拷贝时,参数往后移动一位
 i = 2;
 }
 // 如果要扩展的不是对象或者函数,则定义要扩展的对象为空
 if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
 target = {};
 }
 // 当只含有一个参数时,被扩展的对象是jQuery或jQuery.fn
 if ( length === i ) {
 target = this;
 --i;
 }
 //对从i开始的多个参数进行遍历
 for ( ; i < length; i++ ) {
 // 只处理有定义的值
 if ( (options = arguments[ i ]) != null ) {
 // 展开扩展对象
 for ( name in options ) {
 src = target[ name ];
 copy = options[ name ];
 // 防止循环引用
 if ( target === copy ) {
  continue;
 }
 // 递归处理深拷贝
 if ( deep && copy &&; ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
  if ( copyIsArray ) {
  copyIsArray = false;
  clone = src && jQuery.isArray(src) &#63; src : [];
  } else {
  clone = src && jQuery.isPlainObject(src) &#63; src : {};
  }
  target[ name ] = jQuery.extend( deep, clone, copy );
 // 不处理未定义值
 } else if ( copy !== undefined ) {
  //给target增加属性或方法
  target[ name ] = copy;
 }
 }
 }
 }
 //返回
 return target;
};

jQuery 확장의 원리를 이해하고 나면 앞으로도 jQuery 플러그인 작성에 대해 걱정할 필요가 없을 것이라고 믿습니다.

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