jQuery 소스 분석 2 - JQ 객체에 메소드 및 속성 추가
                                            
 4948 단어  javascript
                    
jQuery.fn = jQuery.prototype = {
    jquery: core_version,  //jquery   
    constructor: jQuery,   //     
    init:  //jquery     ,          DOM     
    selector: //        
    length:  //        DOM     
    toArray:  //         ,               
              //               ,  length  ,jQuery        ,arguments  。
    get: //  jQuery       DOM  ,      DOM  ,
    pushStack: //   DOM       jQuery   prevObject 。
               //this.prevObject=this,   DOM     prevObject   ,  end()     。
    each: //       
    ready: // DOM      ,     
    slice:  //   toArray  ,          pushStack  
    first:  //        jQuery  
    last:  //         jQuery  
    eq:  //      num,   num    jQuery  
    map:   //map                  ,          ,   each  ,  map         , each  
    end:   //    parent()、find()、filter()      jQuery  ,        DOM  
    push: core_push,  //      push  
    sort: [].sort,   //      sort  
    splice: [].splice  //      splice  
}
  위에서 jQuery 초기화의 몇 가지 방법과 속성에 대한 소개를 했습니다. 앞에서 jQuery 대상을 초기화할 때 우리는 jQuery 대상이 사실상 실례화된 jQuery라는 것을 알 수 있습니다.fn.init, 그래서 여기서 주로 init가 어떻게 실현되는지 보고 나머지 방법은 구체적으로 사용할 때 다시 본다.
먼저 init 메서드가 세 개의 매개변수를 가져오는 것을 관찰할 수 있습니다.
init: function( selector, context, rootjQuery ) {...}
  rootjQuery = jQuery(document);//  866 
  init는 수신 선택기를 다음과 같이 구분합니다.
if ( !selector ) {return this;}
  if ( jQuery.isFunction( selector ){//jquery                    
return rootjQuery.ready( selector );}
  if ( selector.selector !== undefined ) {//      select         jQ  
this.selector = selector.selector;
this.context = selector.context;
return jQuery.makeArray( selector, this );}
  return jQuery.makeArray( selector, this );
  다음은 selector가 문자열일 때 어떻게 처리되는지 살펴보겠습니다.
if ( selector.charAt(0) === "" && selector.length >= 3 ) {//     
    match = [ null, selector, null ];
} else {
    match = rquickExpr.exec( selector );
}
if ( match && (match[1] || !context) ) {   //       html  
    if ( match[1] ) { 
        jQuery.merge( this,  jQuery.parseHTML(match[1])   );
        //   parseHTML       DOM     ,    merge DOM        this 。
        if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
                     ,            ,  :
            $('',{'id':'box', 'class':'red'})//                   DOM      。
            //       $        ,                   。
        }
    } else { //   '#id',    js     getElementById  DOM  
        elem = document.getElementById( match[2] );
    }
//         find          。  selector   '.ClassName'
//     jQuery.fn.find->jQuery.find->Sizzle
//     Sizzle  ,  jQuery        ,        ,                ( 
} else if ( !context || context.jquery ) {
    return ( context || rootjQuery ).find( selector );
} else {
    return this.constructor( context ).find( selector );
}
 
             match       
 
 rquickExpr = /^(?:\s*()[^>]*|#([\w-]*))$/; (75 )
match = rquickExpr.exec( selector ); (116 )
  
exec 방법은 정규 매칭에 사용되며, 하나의 그룹을 되돌려줍니다. 첫 번째 요소는 매칭된 문자열이고, 다음 요소는 매칭된 하위 항목입니다. 구체적인 사용법입니다.
밤을 들다.var rquickExpr = /^(?:\s*()[^>]*|#([\w-]*))$/;
console.log( match = rquickExpr.exec( '
' )  );
// ["
", "
", undefined]
console.log( match = rquickExpr.exec( '#id' )  );
// ["#id", undefined, "id"]
  
이제 match는 사실 문자열의 의미를 저장하는 수조라는 것을 알게 되었다. 이것은 사람이 생각해 낸 것이라고 감탄하지 않을 수 없다.정칙이 멍하다.match[1]가 존재하면 html 라벨 을 나타낸다match[2]가 존재하면 id명 을 나타낸다 만약에 두 가지 상황이 모두 일치하지 않는다면 이것은 복잡한 선택기임을 나타낸다. 구체적인 실현은 jQuery 내부의 Sizzle 방법으로 이루어진다. 이 방법은 2천 줄 정도이고 jQuery의 핵심이라고 할 수 있다. 또한 jQuery는 이 방법을 하나의 단독 라이브러리로 여긴다. 만약에 jQuery가 너무 크다고 생각하면 선택기 부분의 기능만 사용할 것이다.관심 있으면 Sizzle 홈페이지에서 다운로드 가능 우리가 평소에 $() 를 호출할 때 시원하고 선택기도 할 수 있고 노드도 만들 수 있다는 것을 알 수 있지만, 이 뒤의 실현 방법이 이렇게 복잡한지 모르겠다. 사용하기에 편리할수록 더욱 복잡해지는 것이다.
응, 위층 말이 맞아-.
흥미가 있으면 저의github를 볼 수 있고, 스타에게 줄 수도 있어요.
                이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
개별 마크다운 블로그 페이지 만들기 - 13부이를 통해 개별 마크다운 기반 블로그 게시물 작성을 시작할 수 있습니다! 이 기사를 따르려면 을 시작점으로 사용하십시오. blog 페이지 디렉토리에 동적 페이지를 생성하여 시작할 수 있습니다. 이 파일[slug].j...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.