Home  >  Article  >  Web Front-end  >  Detailed explanation of javascript modular programming

Detailed explanation of javascript modular programming

PHPz
PHPzOriginal
2017-04-04 14:00:331385browse

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

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(){
  // 代码...
}();

or this method:

+function(){
  // 代码...
}();

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);
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){
  // 代码...
}

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

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 = {}));

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

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

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

 由于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:
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