search
HomeWeb Front-endJS TutorialJavaScript self-executing functions and jQuery extension methods

We usually write the JS code in a separate JS file, and then introduce the file into the page. However, sometimes after introduction, you will encounter problems with variable names or function names that conflict with other JS codes. So how to solve this problem? Scope isolation. In JS, the scope is divided by functions. Encapsulating JS code into functions for calling can avoid the problem of variable name/function name conflicts, but this is not foolproof because the encapsulated function itself may overlap with other functions. Name, solution: self-executing function. This article mainly introduces JavaScript self-executing functions and jQuery extension methods in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

The self-executing function uses a pair of parentheses to wrap the anonymous function. Adding the parentheses (passing parameters) will execute it immediately. Because the function has no name, absolute isolation of scope and conflict of function names are achieved. The basic form is as follows:


(function () {
  console.log('do something');
})();

For example, we wrote some JS logic in the custome.js file and encapsulated it into the function init. We wrap the self-defined function init with a self-executing function, as shown below.


(function () {

  function init() {
    console.log('execute init...');
  }

  init();
})();

When we introduce custome.js in html: , the self-executing function will be executed immediately , and then execute the internally defined init function:

However, the characteristics of immediate execution of self-executing functions make it difficult to call. By defining jQuery extension methods, you can solve this problem and take the initiative in calling and executing self-executing functions.

First let’s take a look at the basic form of defining jQuery extension methods:


jQuery.extend({
  'myMethod': function () {
    console.log('do something');
  }
});

In this way, you can use $.myMethod() or jQuery.myMethod() Call the method defined above.

There is another way to define jQuery extension methods: .fn


jQuery.fn.extend({
  'myMethod': function () {
    console.log('do something');;
  }
});

The extension method defined in the above way needs to be called through the jQuery selector. For example, after understanding JS self-executing functions and jQuery extension methods through the tag selector $("button").myMethod(args)

, we combined the two.

Below we use the feature of immediate execution of the self-executing function to define the jQuery extension method:


(function (jq) {

  function init() {
    console.log('do something');
  }

  jq.extend({
    'myMethod': function () {
      init();
    }
  })
})(jQuery);

Explanation, this self-executing function receives the jQuery object as a parameter , and then internally define an extension method myMethod for jQuery, which executes the real logic code init function

Call:


<script src="jquery-3.2.1.js"></script>
<script src="custome.js"></script>
<script>

 $(function () {
  $.myMethod();
 });

</script>

Description:

After the jQuery file is introduced, the jQuery object is globally available;
The custom JS file custome.js is then introduced, in which the self-executing function receives the jQuery object as a parameter, executes immediately, and internally defines an extension method myMethod for jQuery.
Then we can execute the init function by calling $.meMethod() or jQuery.myMethod() after the page is loaded

Related recommendations:

Self-executing functions in js functions

Pseudo namespace encapsulation method of javascript self-executing functions_javascript skills

Using closures in javascript Solve a large number of global variable problems with self-executing functions_javascript skills

The above is the detailed content of JavaScript self-executing functions and jQuery extension methods. 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
JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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