Detailed explanation of javascript modular programming
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:
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 parametersvar wall = {}; (function(window, WALL, undefined){ })(window, wall);
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.
undefined is as follows:
##
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();
#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();
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
:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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 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.

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 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 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.

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

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.

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.
