Source code analysis of jQuery1.0 using jQuery Constructor (2)

Source: Internet
Author: User

 

Let's continue with the previous jQuery source code analysis (1) and continue to look at the code below.

 

 

JQuery's framework design is very clever. Maybe 1.0 and 1.6.x have great changes in code, but the basic principle is the same. They all use javascript prototype for inheritance, let's look at the following code:

 

 

Function jQuery (a, c ){

 

// Code Segment 1: Several code lines are omitted here

// If the context is global, return a new object

If (window = this)

Return new jQuery (a, c );

 

// Code Segment 2: Several code lines are omitted here

}

 

Here, we omit some unimportant code. jQuery is the entry function.

As you know, javascript Functions are functions and classes. When you create a new function, this function becomes a class constructor. this in the function points to the new instance.

 

While normally calling a global function, this is pointing to the window variable.

 

 

So the above Code is easy to understand.

 

When the jQuery function is called for the first time, jQuery acts as an object factory. when it encounters if (window = this), it immediately creates a new jQuery object, calls jQuery again, and returns the object.

 

When calling the jQuery function for the second time, jQuery acts as the constructor. this points to the new instance.

 

The code itself is okay, but the design is a bit poor. In the position of code segment 1, The jQuery function is called twice, and this is directed to the window and jQuery instance objects respectively, this is a bit bad. Therefore, this is not used in code segment 1, but in code segment 2.

 

 

In line with the single responsibility principle, a function should only do one thing. So later versions of jQuery put the code of the new object into a new function init.

 



Author: baozhifei

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.