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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

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.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles