자신만의 JQuery 프레임워크 개발에 대한 세부정보

黄舟
풀어 주다: 2017-03-01 14:52:20
원래의
1070명이 탐색했습니다.

json 객체를 통한 캡슐화

이것은 다음과 같이 가장 간단한 캡슐화 방법입니다.

<script type="text/javascript">
    /**
    *自执行的匿名函数,可以实现链式调用
    **/
    (function(w){
        var DQuery={            
        &#39;name&#39;:&#39;DQuery&#39;,            
        &#39;version&#39;:&#39;2016-06-05&#39;,            
        &#39;getVersion&#39;:function(){
                console.log(this.version);                
                return this;
            },
            getName:function(){
                console.log(this.name);                
                return this;
            },
            showinfo:function(){
                this.getVersion();                
                this.getName();                
                return this;
            }
        };

        window.DQuery=$$=DQuery; //让外边可以调用
    }(window));    </script>
로그인 후 복사

장점, 간단함, 매우 쉬움 읽다.
단점: DQuery는 생성자가 아닌 객체입니다. DQuery가 출력되면 그 안에 포함된 모든 정보가 노출됩니다(아래 참조). 둘째, 다양한 상황에서 사용할 수 있도록 다양한 객체를 생성하도록 사용자 정의할 수 없습니다.
자신만의 JQuery 프레임워크 개발에 대한 세부정보

생성자를 통한 캡슐화

버전 1

이 버전은 누구나 가장 먼저 떠올리게 될 버전입니다.

(function(w){
        var DQuery=function(){
            this.alias=null;
        }
        DQuery.prototype ={            &#39;name&#39;:&#39;DQuery&#39;,            &#39;version&#39;:&#39;2016-06-05&#39;,            &#39;setAlias&#39;:function(alias){
                this.alias=alias;                return this;
            },            &#39;getAlias&#39;:function(alias){
                console.log(this.alias);                return this;
            },            &#39;getVersion&#39;:function(){
                console.log(this.version);                return this;
            },
            getName:function(){
                console.log(this.name);                return this;
            },
            showinfo:function(){
                this.getVersion();                this.getName();                return this;
            }
        }

        window.DQuery=$$=DQuery; //让外边可以调用
    }(window));
로그인 후 복사

호출 코드는 다음과 같습니다

    var p1= new DQuery();
    p1.alias=&#39;p1&#39;
    var p2= new $$();
    p2.alias=&#39;p2&#39;
    console.log(p1);    console.log(p2);    
    console.log(p1.showinfo==p2.showinfo);    console.log(typeof(DQuery));
로그인 후 복사

효과는 다음과 같습니다
자신만의 JQuery 프레임워크 개발에 대한 세부정보
장점: 출력에서 ​​알 수 있듯이 우선 DQuery는 생성자이고, 이를 통해 해당 매개변수에 따라 다양한 객체를 생성할 수 있습니다. 둘째, DQuery 프로토타입에 정의된 변수와 함수는 모든 객체에 공통적이며 static과 동일합니다.
단점: 객체를 생성할 때마다 새로운 DQuery를 생성해야 하는 것이 조금 번거롭습니다. 둘째, 여전히 약간의 공개가 있습니다.

버전 2

버전 1에서는 객체가 생성될 때마다 새로운 객체가 생성되어야 한다고 가장 먼저 생각하는 것은 객체를 다음과 같이 변경하는 것입니다.

var DQuery=function(){
            this.alias=null;            return  new DQuery();
        }
로그인 후 복사

이렇게 하면 코드 관점에서는 기존 문제는 해결됐지만 새로운 문제가 발생했습니다. 즉, DQuery에서 자신의 객체를 생성하는 것은 재귀 호출과 동일하므로 무한 루프 문제가 발생합니다.
자신만의 JQuery 프레임워크 개발에 대한 세부정보

버전 3

버전 1과 버전 2의 문제점을 고려하여 다음과 같이 개선할 수 있습니다.

(function(w){
        var DQuery=function(alias){
            this.alias=alias;            return new DQuery.prototype.init();
        }
        DQuery.prototype ={            &#39;name&#39;:&#39;DQuery&#39;,            &#39;version&#39;:&#39;2016-06-05&#39;,            &#39;init&#39;:function(){

            },            &#39;setAlias&#39;:function(alias){
                this.alias=alias;                return this;
            },            &#39;getAlias&#39;:function(alias){
                return this;
            },            &#39;getVersion&#39;:function(){
                return this.version;
            },
            getName:function(){
                return this.name;
            },
            showinfo:function(){
                return this.name+&#39;:&#39;+this.version;
            }
        }

        window.DQuery=$$=DQuery; //让外边可以调用
    }(window));

    console.log(typeof($$));//$$是一个构造函数
    console.log(typeof($$()));//$$()返回一个对象
    console.log(typeof(new $$()));//new $$()返回一个对象

    var p1=$$(&#39;id1&#39;);	var p2=new $$(&#39;id2&#39;);
로그인 후 복사

장점: 버전 1 및 버전 2 버전 2에서는 기존 문제가 해결되었습니다.
단점: 클래스(생성자 내)의 속성과 메서드를 호출할 수 없습니다.

버전 4

new로 생성된 객체의 경우 객체의 범위는 함수의 범위이며 프로토타입도 생성자의 프로토타입입니다(자세한 내용은 보충 내용) new DQuery.prototype.init();을 사용했기 때문에 반환된 객체의 프로토타입은 init 함수의 프로토타입과 동일합니다. 하지만 우리는 그것이 DQuery 함수의 프로토타입을 가리키기를 원합니다. 이 시점에서 두 가지 접근 방식이 있습니다.
옵션 1: init 메서드에서 DQuery 개체를 가리키는 이것을 반환하지만, 이 조건에서는 수행하기 어렵습니다. 왜냐하면 사용자가 다음을 통해 개체를 생성한다고 확신하기 때문입니다. new DQuery 또는 DQuery()를 직접 호출하여 객체를 생성합니다
옵션 2: init.prototype=DQuery.prototype을 설정할 수 있으므로 init 생성자를 사용하여 객체가 생성되더라도 객체의 프로토타입은 다음과 동일합니다. DQuery의 그것.
버전 3을 개선한 후 코드는 다음과 같습니다.

(function(w){
        var DQuery=function(alias){
            this.alias=alias;            
            return new DQuery.prototype.init();
        }
        DQuery.prototype ={            
        &#39;self&#39;:this,            
        &#39;name&#39;:&#39;DQuery&#39;,            
        &#39;version&#39;:&#39;2016-06-05&#39;,            
        &#39;init&#39;:function(){

            },            &#39;setAlias&#39;:function(alias){
                this.alias=alias;                return this;
            },            &#39;getAlias&#39;:function(alias){
                return this;
            },            &#39;getVersion&#39;:function(){
                return this.version;
            },
            getName:function(){
                return this.name;
            },
            showinfo:function(){
                return this.name+&#39;:&#39;+this.version;
            }
        }
        DQuery.prototype.init.prototype=DQuery.prototype;
        window.DQuery=$$=DQuery; //让外边可以调用
    }(window));

    console.log(typeof($$));//$$是一个构造函数
    console.log(typeof($$()));//$$()返回一个对象
    console.log(typeof(new $$()));//new $$()返回一个对象
    var p1=new DQuery();
    console.log(p1);
    console.log(p1 instanceof DQuery); //true
로그인 후 복사

자신만의 JQuery 프레임워크 개발에 대한 세부정보
우리의 요구 사항을 완벽하게 충족하고 위의 문제를 해결한 것을 확인할 수 있습니다.

버전 5

처음에는 버전 4에는 문제가 없는 줄 알았는데, 결국 버전 4에도 여전히 작은 문제가 있다는 것을 알게 되었습니다. 즉, 반환된 개체가 속성에 액세스할 수 없다는 것입니다. DQuery 생성자에 의해 정의됩니다. 이 문제를 해결하려면 전화나 신청을 통해 해결할 수 있습니다. 물론 실제로는 필요하지 않습니다. 왜냐하면 init 메소드에서 일부 속성을 직접 정의할 수 있기 때문입니다. 왜 DQuery에서 속성을 정의하고 문제를 일으키나요?
****다음 버전은 계속 추가됩니다********** * **

요약

대략적인 관계도는 다음과 같습니다
자신만의 JQuery 프레임워크 개발에 대한 세부정보
간략화된 코드는 다음과 같습니다

(function(w){
        var DQuery=function(){
            return new DQuery.prototype.init();
        }
        DQuery.prototype ={            //定义一些静态变量
            &#39;self&#39;:this,            &#39;name&#39;:&#39;DQuery&#39;,            &#39;version&#39;:&#39;2016-06-05&#39;,            // 构造函数方法
            &#39;init&#39;:function(){
                //定义一些变量属性
            },            //定义一些方法
            &#39;setAlias&#39;:function(alias){
                this.alias=alias;                return this;
            }           
        }
        DQuery.prototype.init.prototype=DQuery.prototype;
        window.DQuery=$$=DQuery; //让外边可以调用
    }(window));
로그인 후 복사

보충

생성자의 반환 값이 새 개체에 미치는 영향

먼저 새 개체의 프로세스를 요약해 보겠습니다. 예를 들어 Student 생성자를 사용하여 var s1=new Student() 개체를 만드는 과정은 다음과 같이 요약할 수 있습니다. 먼저 새 개체를 만들고 두 번째로 생성자의 범위를 새 개체에 할당합니다(따라서 이는 새 개체를 가리킵니다. Student.prototype은 객체 프로토타입에 할당됩니다. 그런 다음 객체를 s1에 할당합니다.

생성자에 지정된 반환 값이 없습니다

이 경우 기본적으로 새 개체 인스턴스가 반환됩니다.

생성자에 지정된 반환 값이 있습니다

1. 반환 값이 기본 데이터 유형인 경우에도 새 객체 인스턴스가 반환됩니다.
2. 반환값이 객체인 경우 반환된 객체는 지정된 객체값이 됩니다. 이 경우 이 값이 참조하는 개체는 삭제됩니다.
3. 함수를 반환하는 경우 new는 객체를 반환하지 않고 함수를 반환합니다.

//无返回值
    function Student1(){
        this.name=&#39;dqs&#39;;
    }    var p1=new Student1();
    console.log(typeof(p1));//object
    console.log(&#39;name&#39; in p1 ); //true
    console.log(p1 instanceof Student1 ); //true

    //返回function
    function Student2(){
        this.name=&#39;dqs&#39;;        return function(){};
    }    var p2=new Student2();

    console.log(typeof(p2));//function
    console.log(p2 instanceof Student2 ); //false
    //返回基本类型

    //返回基本类型
    function Student3(){
        this.name=&#39;dqs&#39;;        return &#39;nihao&#39;;
    }    var p3=new Student3();
    console.log(typeof(p3));//object
    console.log(&#39;name&#39; in p3 ); //true
    console.log(p3 instanceof Student3 ); //true

    //返回对象类型
    function Student4(){
        this.name=&#39;dqs&#39;;        return {&#39;location&#39;:&#39;hsd&#39;};
    }    var p4=new Student4();
    console.log(typeof(p4));//object
    console.log(&#39;name&#39; in p4 ); //false
    console.log(p3 instanceof Student4 ); //false
로그인 후 복사


위 내용은 JQuery 프레임워크 개발에 대한 내용입니다. 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!