Home Web Front-end JS Tutorial Parse core function instances in jquery

Parse core function instances in jquery

Jun 17, 2017 pm 05:49 PM
jquery depth parse

Core functions include:

How jquery is defined, how to call it, and how to extend it. Mastering how the core methods are implemented is the key to understanding the jQuery source code. Everything suddenly became clear here.

1, how to define, that is, the entrance

// Define a local copy of jQuery

var jQuery = function(selector, context) {

// The jQuery object is actually just the init constructor 'enhanced'

return new jQuery.fn.init( selector, context, rootjQuery ); // The jQuery object is actually just the constructor FunctionjQuery.prototype.init enhanced version

}

2, jQuery prototype, and its relationship with jQuery.fn.init

//Define object method, that is, it can only be called through $("xx").

jQuery.fn = jQuery.prototype = {

init:function( selector, context, rootjQuery ) {

return jQuery.makeArray( selector, this );

}

There are many other properties and methods,

Properties include: jquery, constructor, selector, length

Methods include: toArray,get, pushStack,each, ready,slice, first,last,eq, map,end, push, sort, splice

}

//put jQuery.prototype is assigned to jQuery.prototype.init.prototype for later instantiation

// Give the init function the jQuery prototype for later instantiation

jQuery.fn.init.prototype = jQuery.fn;

That is, $("xx") has an instance method and can be called. (Call the method defined under jQuery.prototype)

Why does jQuery return the jQuery.fn.init object?

jQuery = function( selector, context ) {

// The jQuery object is actually just the init constructor 'enhanced'

return new jQuery.fn.init( selector, context, rootjQuery );

}

jQuery.fn = jQuery.prototype = {

……

}

jQuery.fn.init.prototype = jQuery.fn;

Find similar questions on stackoverflow :

http://stackoverflow.com/questions/4754560/help-understanding-jquerys-jquery-fn-init-why-is-init-in-fn

And this

http://stackoverflow.com/questions/1856890/why-does-jquery-use-new-jquery-fn-init-for-creating-jquery-object-but-i-can/1858537#1858537

I believe the code is written in this fashion so that the new keyword is not required each time you instantiate a new jQuery object and also to delegate the logic behind the object construction to the prototype. The former I believe is to make the library cleaner to use and the latter to keep the initialisation logic cleanly in one place and allow init to be recursively called to construct and return an object that correctly matches the passed arguments.

3, extend extended object method and static method principle

jQuery.extend = jQuery.fn.extend = function() {

var target = arguments[0] || {};

Return target;

}

It is convenient to use extend, which is nothing more than $.extend({}); and $.fn.extend({}); If you It would be great if you could understand and think of jQuery.prototype when you see fn.

Let’s look at this scope again:

$.extend ->this is $-> this.aa()

$.fn.extend-> ;this is $.fn-> this.aa()

Attached extend implementation details:

Usage scenarios:

1, extend some functions

Only one parameter. For example: $.extend({f1:function(){},f2:function(){},f3:function(){}})

2, merge multiple objects into the first object

(1) Shallow copy, the first parameter is the target object. For example

var a = {name:”hello”}

var b = {age:30}

$.extend(a,b);//a= {name:”hello”,age:30}

(2) Deep copy, the first parameter is TRUE, and the second parameter is the target object. For example

var a = {name:{job:”it”}};

var b = {name:{age: 30 }};

//$ .extend(a,b);

$.extend(true,a,b);

console.log(a);

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

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 ) {//$.extend({f1:function(){},f2:function(){},f3:function(){}})

        target = this;//this是$,或是$.fn

        --i;

    }

 

    for ( ; i < length; i++ ) {//可能有多个对象扩展到第一个对象上

        // Only deal with non-null/undefined values

        if ( (options = arguments[ i ]) != null ) {//options是一个对象

            // Extend the base object

            for ( name in options ) {

                src = target[ name ];  //src是target里已经存在的value(也可能不存在)

                copy = options[ name ];//copy是待合入的一个value

 

                // 防止循环引用  Prevent never-ending loop

                if ( target === copy ) {//例如:var a={};$.extend(a,{name:a});//可能导致循环引用

                    continue;

                }

 

                // if是深复制else是浅复制  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) ? src : [];

 

                    else {

                        clone = src && jQuery.isPlainObject(src) ? src : {};

                    }

 

                    // 亮了,直至剥离至最深一层非对象类型,而且是逐个。Never move original objects, clone them

                    target[ name ] = jQuery.extend( deep, clonecopy );

 

                // Don't bring in undefined values

                else if copy !== undefined ) {

                    target[ name ] = copy;//target[ name ] = options[ name ];

                }

            }

        }

    }

 

    // Return the modified object

    return target;

};

Copy after login

jQuery. extend({...}) analysis

Look at how it is written

jQuery.extend({

prop:””

method:function( ){}

});

It can be seen that these methods are static properties and methods of jQuery (that is, tool methods). In the future, they can be provided directly to users or For internal use.

The specific implemented tool properties and methods are (also marked which ones are used internally)

jQuery.extend({

expando : Generate unique JQ string(internal)

noConflict() : Prevent conflicts

isReady : Whether the DOM has been loaded (internal)

readyWait : Counter of how many files to wait for (internal)

holdReady() : Delay DOM trigger

ready() : Prepare for DOM trigger

isFunction() : Whether it is a function

isArray() : Whether it is an array

isWindow() : Whether it is a window

isNumeric() : Whether it is an array Number

type() : Determine the data type

isPlainObject() : Whether it is an object argument

isEmptyObject() : Whether it is an empty object

error() : Throw an exception

parseHTML() : Parse node

parseJSON() : Parse JSON

parseXML () : Parse XML

noop() : Empty function

globalEval() : Global parsing JS

camelCase() : Convert camel case

nodeName( ) : Whether it is the specified node name (internal)

each() : Traverse the collection

trim() : Remove leading and trailing spaces

makeArray() : Convert a class array to a true array

inArray() : Array version indexOf

merge() : Merge arrays

grep() : Filter new array

map() : Map new Array

guid : unique identifier (internal)

proxy() : change this to point to

access() : multi-function value operation (internal)

now() : Current time

swap() : CSS swap (internal)

});

jQuery.ready.promise = function(){}; Monitoring Asynchronous operation of DOM (internal)

function isArraylike(){} Array-like judgment (internal)

The above is the detailed content of Parse core function instances in jquery. For more information, please follow other related articles on the PHP Chinese website!

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)

Detailed explanation of Oracle error 3114: How to solve it quickly Detailed explanation of Oracle error 3114: How to solve it quickly Mar 08, 2024 pm 02:42 PM

Detailed explanation of Oracle error 3114: How to solve it quickly, specific code examples are needed. During the development and management of Oracle database, we often encounter various errors, among which error 3114 is a relatively common problem. Error 3114 usually indicates a problem with the database connection, which may be caused by network failure, database service stop, or incorrect connection string settings. This article will explain in detail the cause of error 3114 and how to quickly solve this problem, and attach the specific code

Parsing Wormhole NTT: an open framework for any Token Parsing Wormhole NTT: an open framework for any Token Mar 05, 2024 pm 12:46 PM

Wormhole is a leader in blockchain interoperability, focused on creating resilient, future-proof decentralized systems that prioritize ownership, control, and permissionless innovation. The foundation of this vision is a commitment to technical expertise, ethical principles, and community alignment to redefine the interoperability landscape with simplicity, clarity, and a broad suite of multi-chain solutions. With the rise of zero-knowledge proofs, scaling solutions, and feature-rich token standards, blockchains are becoming more powerful and interoperability is becoming increasingly important. In this innovative application environment, novel governance systems and practical capabilities bring unprecedented opportunities to assets across the network. Protocol builders are now grappling with how to operate in this emerging multi-chain

Analysis of the meaning and usage of midpoint in PHP Analysis of the meaning and usage of midpoint in PHP Mar 27, 2024 pm 08:57 PM

[Analysis of the meaning and usage of midpoint in PHP] In PHP, midpoint (.) is a commonly used operator used to connect two strings or properties or methods of objects. In this article, we’ll take a deep dive into the meaning and usage of midpoints in PHP, illustrating them with concrete code examples. 1. Connect string midpoint operator. The most common usage in PHP is to connect two strings. By placing . between two strings, you can splice them together to form a new string. $string1=&qu

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Analysis of new features of Win11: How to skip logging in to Microsoft account Analysis of new features of Win11: How to skip logging in to Microsoft account Mar 27, 2024 pm 05:24 PM

Analysis of new features of Win11: How to skip logging in to a Microsoft account. With the release of Windows 11, many users have found that it brings more convenience and new features. However, some users may not like having their system tied to a Microsoft account and wish to skip this step. This article will introduce some methods to help users skip logging in to a Microsoft account in Windows 11 and achieve a more private and autonomous experience. First, let’s understand why some users are reluctant to log in to their Microsoft account. On the one hand, some users worry that they

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Apache2 cannot correctly parse PHP files Apache2 cannot correctly parse PHP files Mar 08, 2024 am 11:09 AM

Due to space limitations, the following is a brief article: Apache2 is a commonly used web server software, and PHP is a widely used server-side scripting language. In the process of building a website, sometimes you encounter the problem that Apache2 cannot correctly parse the PHP file, causing the PHP code to fail to execute. This problem is usually caused by Apache2 not configuring the PHP module correctly, or the PHP module being incompatible with the version of Apache2. There are generally two ways to solve this problem, one is

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

See all articles