Table of Contents
Encapsulation through json objects
Encapsulation through constructor
Version 5
Version Three
Summary
Supplement
The impact of the return value of the constructor on a new object
There is no return value specified in the constructor
There is a specified return value in the constructor
Home Web Front-end JS Tutorial Details on developing your own JQuery framework

Details on developing your own JQuery framework

Mar 01, 2017 pm 02:52 PM

Encapsulation through json objects

This is the simplest way of encapsulation, as follows:

<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>
Copy after login

Advantages, simple, very Easy to read.
Disadvantages: DQuery is an object, not a constructor. When DQuery is output, all the information contained in it is exposed (as shown below). Secondly, it cannot be customized accordingly to generate different objects to meet use in different situations.
Details on developing your own JQuery framework

Encapsulation through constructor

Version 1

This version is the first version that everyone will think of. The program is as follows:

(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));
Copy after login

The calling code is as follows

    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));
Copy after login

The effect is as follows
Details on developing your own JQuery framework
Advantages: As can be seen from the output, first of all, DQuery is a constructor, which allows us to generate different objects according to the corresponding parameters. Secondly, the variables and functions defined in DQuery's prototype are common to all objects and are equivalent to static.
Disadvantages: It is a bit troublesome to have to create a new DQuery every time you create an object. Secondly, it’s still a bit revealing.

Version 2

In version 1, every time an object is created, a new one must be created. Maybe the first thing we think of is to change it to the following:

var DQuery=function(){
            this.alias=null;            return  new DQuery();
        }
Copy after login

In this way, From the code point of view, the existing problems have been solved, but a new problem has arisen. That is, because creating its own object in DQuery is equivalent to a recursive call, an infinite loop problem occurs.
Details on developing your own JQuery framework

Version Three

In view of the problems in Version One and Version Two, the following improvements can be made

(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;);
Copy after login

Advantages: Version One and Version Two are solved problems existing in.
Disadvantages: Properties and methods in the class (in the constructor) cannot be called.

Version 4

For an object created by new, the scope in the object is the scope of the function, and its prototype is also the prototype of the constructor (for details, please refer to the supplementary content), then, since we Using new DQuery.prototype.init();, the prototype of the returned object is equal to the prototype of the init function. But we want it to point to the prototype of the DQuery function. At this point, there are two approaches:
Option 1: In the init method, we return this pointing to the DQuery object, but this is difficult to do under this condition, because I am sure that the user creates the object through new DQuery Or call DQuery() directly to create the object
Option 2: We can set init.prototype=DQuery.prototype, so that although the object is created using the init constructor, the prototype of the object is the same as that of DQuery.
So after version three was improved, the code is as follows:

(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
Copy after login

Details on developing your own JQuery framework
It can be found that it fully meets our requirements and solves the above problems.

Version 5

At first I thought there was no problem with version 4, but finally I found that version 4 still had a small problem, that is, the returned object could not access the properties defined by the DQuery constructor. To solve this problem, we can solve it by calling or applying. Of course, it is actually not necessary, because we can directly define some properties in the init method. Why define them in DQuery and then cause trouble for ourselves.
****Will continue to be added in subsequent versions*********** **

Summary

The approximate relationship diagram is as follows
Details on developing your own JQuery framework
The simplified code is as follows:

(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));
Copy after login

Supplement

The impact of the return value of the constructor on a new object

First, let’s summarize the process of new an object. For example, use the Student constructor to create an object var s1=new Student(). The process can be summarized as follows: first create a new object, and secondly assign the scope of the constructor to the new object (so this points to this new object , and Student.prototype is assigned to the prototype of the object), and then assigns the object to s1.

There is no return value specified in the constructor

In this case, a new object instance will be returned by default.

There is a specified return value in the constructor

1. If the return value is a basic data type, a new object instance will still be returned.
2.. If the return value is an object, the returned object becomes the specified object value. In this case, the object referenced by this value is discarded.
3. If you return a function, new will not return an object, but the function.

//无返回值
    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
Copy after login


The above is the details of developing your own JQuery framework. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to evaluate the cost-effectiveness of commercial support for Java frameworks How to evaluate the cost-effectiveness of commercial support for Java frameworks Jun 05, 2024 pm 05:25 PM

Evaluating the cost/performance of commercial support for a Java framework involves the following steps: Determine the required level of assurance and service level agreement (SLA) guarantees. The experience and expertise of the research support team. Consider additional services such as upgrades, troubleshooting, and performance optimization. Weigh business support costs against risk mitigation and increased efficiency.

How does the learning curve of PHP frameworks compare to other language frameworks? How does the learning curve of PHP frameworks compare to other language frameworks? Jun 06, 2024 pm 12:41 PM

The learning curve of a PHP framework depends on language proficiency, framework complexity, documentation quality, and community support. The learning curve of PHP frameworks is higher when compared to Python frameworks and lower when compared to Ruby frameworks. Compared to Java frameworks, PHP frameworks have a moderate learning curve but a shorter time to get started.

Performance comparison of Java frameworks Performance comparison of Java frameworks Jun 04, 2024 pm 03:56 PM

According to benchmarks, for small, high-performance applications, Quarkus (fast startup, low memory) or Micronaut (TechEmpower excellent) are ideal choices. SpringBoot is suitable for large, full-stack applications, but has slightly slower startup times and memory usage.

How do the lightweight options of PHP frameworks affect application performance? How do the lightweight options of PHP frameworks affect application performance? Jun 06, 2024 am 10:53 AM

The lightweight PHP framework improves application performance through small size and low resource consumption. Its features include: small size, fast startup, low memory usage, improved response speed and throughput, and reduced resource consumption. Practical case: SlimFramework creates REST API, only 500KB, high responsiveness and high throughput

Golang framework documentation best practices Golang framework documentation best practices Jun 04, 2024 pm 05:00 PM

Writing clear and comprehensive documentation is crucial for the Golang framework. Best practices include following an established documentation style, such as Google's Go Coding Style Guide. Use a clear organizational structure, including headings, subheadings, and lists, and provide navigation. Provides comprehensive and accurate information, including getting started guides, API references, and concepts. Use code examples to illustrate concepts and usage. Keep documentation updated, track changes and document new features. Provide support and community resources such as GitHub issues and forums. Create practical examples, such as API documentation.

How to choose the best golang framework for different application scenarios How to choose the best golang framework for different application scenarios Jun 05, 2024 pm 04:05 PM

Choose the best Go framework based on application scenarios: consider application type, language features, performance requirements, and ecosystem. Common Go frameworks: Gin (Web application), Echo (Web service), Fiber (high throughput), gorm (ORM), fasthttp (speed). Practical case: building REST API (Fiber) and interacting with the database (gorm). Choose a framework: choose fasthttp for key performance, Gin/Echo for flexible web applications, and gorm for database interaction.

Java Framework Learning Roadmap: Best Practices in Different Domains Java Framework Learning Roadmap: Best Practices in Different Domains Jun 05, 2024 pm 08:53 PM

Java framework learning roadmap for different fields: Web development: SpringBoot and PlayFramework. Persistence layer: Hibernate and JPA. Server-side reactive programming: ReactorCore and SpringWebFlux. Real-time computing: ApacheStorm and ApacheSpark. Cloud Computing: AWS SDK for Java and Google Cloud Java.

What are the common misunderstandings in the learning process of Golang framework? What are the common misunderstandings in the learning process of Golang framework? Jun 05, 2024 pm 09:59 PM

There are five misunderstandings in Go framework learning: over-reliance on the framework and limited flexibility. If you don’t follow the framework conventions, the code will be difficult to maintain. Using outdated libraries can cause security and compatibility issues. Excessive use of packages obfuscates code structure. Ignoring error handling leads to unexpected behavior and crashes.

See all articles