Table of Contents
IFE explanation" >1. IIFE explanation
2. The meaning of brackets
4.1 Common writing method
五、分文件加载IIFE要注意的点
Home Web Front-end JS Tutorial Detailed explanation of javascript modular programming

Detailed explanation of javascript modular programming

Apr 04, 2017 pm 02:00 PM

1. IIFE explanation

Full spelling of Imdiately Invoked Function Expression, immediately executed function expression.

As shown in the following code, it is an anonymous immediately executed function:

(function(window, undefined){
  // 代码...    
})(window);
Copy after login

2. The meaning of brackets

2.1 Wrapping The meaning of the brackets for function(){}

The purpose of this bracket is to convert function(){} into an expression. Like the source code of some libraries, I like to use the following method instead:

~function(){
  // 代码...
}();
Copy after login

or this method:

+function(){
  // 代码...
}();
Copy after login

In fact, the effect is the same, they are all function(){}Convert into an executable expression for easy execution.
If you remove the brackets, an error will be reported. Because a simple function(){} is not an executable expression, an error will be reported directly. As shown below:

Detailed explanation of javascript modular programming


2.1 The meaning of the second bracket

Understand After understanding the meaning of the first bracket, the second bracket is very simple, it is to execute the expression.

3. The meaning of parameters

Take this code as an example to explain the parameters

var wall = {};
(function(window, WALL, undefined){

})(window, wall);
Copy after login
Parameters are divided into formal parameters and actual parameters.


function(window, WALL, undefined)The three parameters are formal parameters, and the two parameters in the second bracket (window, wall) are actual parameters. can also be understood as
window == window, wall == WALL.

2.1 Ordinary formal parameters

Ordinary formal parameters refer to actual

variables such as window and wall Pass in the specification, which can be any type of variable. A formal parameter corresponds to an actual parameter



2.2 Special formal parameter undefined

Why do we need to write an extra undefined for the formal parameter? This is a very interesting topic.

As you can see in this example, there are only two actual parameters and three formal parameters. Therefore, when the function is executed, the formal parameter
undefined will be assigned the value undefined by default.

The function of the formal parameter

undefined is as follows: ## 

2.2.1 Prevent the special value undefined from being tampered with by malicious code.

In lower version browsers such as IE6, undefined can be modified. After this special value is modified, judgments like the following will become invalid.

if(wall == undefined){
  // 代码...
}
Copy after login

Therefore, the purpose of adding an extra formal parameter here is to prevent this situation from happening. As long as it is within this IIFE scope, undefined can be obtained normally.

2.2.2 Compressed code can compress undefined

# ## Because undefined is used as a formal parameter, code compression tools like YUI compressor can compress its related values ​​and reduce Small file size. 4. Writing analysis



4.1 Common writing method

var wall = {}; // 声明定义一个命名空间wall

// 定义方法
(function(window, WALL, undefined){
    // 给wall命名空间绑定方法say
    WALL.say = function(){
        console.log('hello');
    };
})(window, wall);

(function(window, WALL, undefined){
    // 给wall命名空间绑定方法 whoIam
    WALL.whoIam = function(){
        console.log('wall');
    };
})(window, wall);

// 调用
wall.say();
wall.whoIam();
Copy after login
First define a namespace, and then add things to this namespace. This is the most common way of writing and the easiest to understand. The disadvantage is that a namespace must be declared before the relevant binding code can be executed. There is a problem with sequential loading.


#4.2 Amplification mode

var wall = (function(window, WALL, undefined){
    if(typeof WALL == 'undefined'){
        WALL = {};
    }

    // 给wall命名空间绑定方法say
    WALL.say = function(){
        console.log('hello');
    }

    return WALL; // 返回引用
})(window, wall);

var wall = (function(window, WALL, undefined){
    if(typeof WALL == 'undefined'){
        WALL = {};
    }

    // 给wall命名空间绑定方法 whoIam
    WALL.whoIam = function(){
        console.log('wall');
    }

    return WALL; // 返回引用
})(window, wall);

// 调用
wall.say();
wall.whoIam();
Copy after login
# ## The advantage of the amplification mode is that you don’t need to consider the order in which the code is loaded. Because js allows repeated var declarations for

wall
variables, this code can be executed. I can split the IIFE function into multiple files for loading without the problems that need to be paid attention to in ordinary writing. #Points to note
:

1. The header of IIFE must first check whether the namespace has been instantiated. If it has not been instantiated, instantiate it.

2. At the end of the IIFE, a reference to the namespace must be returned, so that subsequent code can get the latest wall namespace content.

4.3 Wide-enlargement mode

(function(window, WALL, undefined){
    // 给wall命名空间绑定方法say
    WALL.say = function(){
        console.log('hello');
    }
})(window, window.wall || (window.wall = {}));

(function(window, WALL, undefined){
    // 给wall命名空间绑定方法 whoIam
    WALL.whoIam = function(){
        console.log('wall');
    }
})(window, window.wall || (window.wall = {}));

// 调用
wall.say();
wall.whoIam();
Copy after login
# ## 

The key points to pay attention to in the wide-enlargement mode: It is the window.wall in the actual parameter section || (window.wall = {})

.

Use the ||operator for trickery. If window.wall
has been instantiated, it is not defined. Then directly return the reference of window.wall and assign it to the formal parameter
WALL. Content following the || operator will not be executed. If window.wall has not been instantiated yet, instantiate it. The point to note here is that instantiation is an assignment operation, which needs to be wrapped in parentheses and turned into an expression to execute, so that no error will be reported. Expression (window.wall = {})
After execution is completed, a reference to the new object
window.wall will be returned.

宽放大模式的好处:是可以切割成多个文件进行加载,而不必考虑文件加载的先后顺序,不存在强耦合关系。
 当然,如果IIFE里面的方法互相引用,还是存在加载依赖的问题。这个问题可以用加载器Require.js等工具解决,这里就不讨论了。

五、分文件加载IIFE要注意的点

;(function(window, WALL, undefined){
    // 给wall命名空间绑定方法say
    WALL.say = function(){
        console.log('hello');
    }
})(window, window.wall || (window.wall = {}));
Copy after login

 眼尖的已经看出区别了,就是文件开始的地方,先写上分号;
 这样,多个文件合并的时候,才不会出现收尾相接,代码出现错乱的问题。比如下面这种情况:

// a.js 文件
wall.log()

// b.js 文件
(function(window, WALL, undefined){
    // 给wall命名空间绑定方法say
    WALL.say = function(){
        console.log('hello');
    }
})(window, window.wall || (window.wall = {}));
Copy after login

 由于a.js文件的wall.log()少写了分号,跟b.js文件合并后,js就会认为‘wall.log()(...)’是需要这么执行的,结果代码就报错了。


 觉得不错的,可以关注<a href="http://www.php.cn/js/js-weixinapp-module.html" target="_blank">模块化</a>这个系列的文章,容我后续码字,敬请期待!


The above is the detailed content of Detailed explanation of javascript modular programming. 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)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 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.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

How do I install JavaScript? How do I install JavaScript? Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles