search
HomeWeb Front-endJS TutorialIn-depth analysis of the core functions in jquery

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);

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 <p>jQuery. extend({...}) analysis<br><br>Look at how it is written</p><p>jQuery.extend({</p><p>prop:””</p><p>method:function( ){}</p><p>});</p><p>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. </p><p>The specific implemented tool properties and methods are (also marked which ones are used internally)</p><p>jQuery.extend({<br><br> expando : Generate unique JQ<a href="http://www.php.cn/wiki/57.html" target="_blank"> string</a>(internal)<br><br> noConflict() : Prevent conflicts<br><br> isReady : Whether the DOM has been loaded (internal)<br><br> readyWait : Counter of how many files to wait for (internal)<br><br> holdReady() : Delay DOM trigger<br><br> ready() : Prepare for DOM trigger<br><br> isFunction() : Whether it is a function<br><br> isArray() : Whether it is an array<br><br> isWindow() : Whether it is a window<br><br> isNumeric() : Whether it is an array Number <br><br> type() : Determine the <a href="http://www.php.cn/code/5808.html" target="_blank"> data type</a><br><br> isPlainObject() : Whether it is an object argument<br><br> isEmptyObject() : Whether it is an empty object <br><br> error() : <a href="http://www.php.cn/php/php-tp-throw.html" target="_blank">Throw an exception</a><br><br> parseHTML() : Parse node<br><br> parseJSON() : Parse JSON<br><br> parseXML () : Parse XML<br><br> noop() : Empty function<br><br> globalEval() : Global parsing JS<br><br> camelCase() : Convert camel case<br><br> nodeName( ) : Whether it is the specified node name (internal)<br><br> each() : Traverse the collection<br><br> trim() : Remove leading and trailing spaces<br><br> makeArray() : Convert a class array to a true array <br><br> inArray() : Array version indexOf<br><br> merge() : Merge arrays<br><br> grep() : Filter new array<br><br> map() : Map new Array<br><br> guid : unique identifier (internal)<br><br> proxy() : change this to point to<br><br> access() : multi-function value operation (internal)<br><br> now() : Current time<br><br> swap() : CSS swap (internal)<br><br>});</p><p>jQuery.ready.promise = function(){}; Monitoring Asynchronous operation of DOM (internal)</p><p>function isArraylike(){} Array-like judgment (internal)</p>

The above is the detailed content of In-depth analysis of the core functions in jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software