search
HomeBackend DevelopmentPHP Tutorialjavascript modular programming reprint

Javascript Modular Programming

Author: Ruan Yifeng Published: 2013-01-08 18:04 Read: 7632 times Recommended: 40 Original link [Collection]

As websites gradually become "Internet applications" "Program", the Javascript code embedded in web pages is becoming larger and more complex.

  Web pages are becoming more and more like desktop programs, requiring a team's division of labor and collaboration, progress management, unit testing, etc... Developers have to use software engineering methods to manage the business logic of web pages.

 Javascript modular programming has become an urgent need. Ideally, developers only need to implement the core business logic, and other modules can be loaded by others.

 However, Javascript is not a modular programming language. It does not support "classes", let alone "modules". (The sixth edition of the ECMAScript standard, which is being formulated, will officially support "classes" and "modules", but it will take a long time to be put into practice.)

 The Javascript community has made a lot of efforts. In the existing operating environment, To achieve the effect of "module". This article summarizes the current best practices of "Javascript modular programming" and explains how to put them into practice. Although this is not an introductory tutorial, it can be understood as long as you have a basic understanding of Javascript syntax.

1. Original writing

A module is a set of methods that implement specific functions.

  As long as different functions (and variables that record status) are simply put together, it is considered a module.

function m1(){
  //...
}
function m2(){
  //...
} 

 The above functions m1() and m2() form a module. When using it, just call it directly.

 The disadvantages of this approach are obvious: it "pollutes" global variables, there is no guarantee that variable names will not conflict with other modules, and there is no direct relationship between module members.

2. Object writing method

In order to solve the above shortcomings, the module can be written as an object, and all module members are placed in this object.

var module1 = new Object ({
  _count : 0,
  m1 : function (){
    //...
  },
  m2 : function (){
    //...
  }
}); 

 The above functions m1() and m2() are both encapsulated in the module1 object. When used, it is to call the properties of this object:

module1.m1(); 

 However, this way of writing will expose all module members, and the internal state can be rewritten externally. For example, external code can directly change the value of an internal counter.

module1._count = 5; 

3. How to write an immediately executed function

Using "Immediately-Invoked Function Expression (IIFE)" can achieve the purpose of not exposing private members.

var module1 = (function(){
  var _count = 0;
  var m1 = function(){
    //...
  };
  var m2 = function(){
    //...
  };
  return {
  m1 : m1,
  m2 : m2
  };
})(); 

Using the above writing method, external code cannot read the internal _count variable.

console.info (module1._count); //undefined

 Module1 is the basic writing method of Javascript module. Next, we will process this writing method.

4. Amplification Mode

If a module is very large and must be divided into several parts, or one module needs to inherit another module, then it is necessary to use "augmentation mode".

var module1 = (function (mod){
  mod.m3 = function () {
    //...
  };
  return mod;
})(module1); 

 The above code adds a new method m3() to the module1 module, and then returns the new module1 module.

5. Loose augmentation

In the browser environment, each part of the module is usually obtained from the Internet, and sometimes it is impossible to know which part will be loaded first. If the writing method in the previous section is used, the first executed part may load a non-existent empty object, in which case the "widening mode" must be used.

var module1 = ( function (mod){
  //...
  return mod;
})(window.module1 {}); 

Compared with "enlargement mode", "wide enlargement mode" means that the parameters of "immediate execution function" can be empty objects.

6. Input global variables

Independence is an important feature of the module. It is best not to directly interact with other parts of the program inside the module.

 In order to call global variables inside a module, other variables must be explicitly entered into the module.

var module1 = (function ($, YAHOO) {
  //...
})(jQuery, YAHOO); 

 The above module1 module needs to use the jQuery library and the YUI library, so these two libraries (actually two modules) are input into module1 as parameters. In addition to ensuring the independence of the modules, this also makes the dependencies between modules obvious. For more discussion in this regard, see Ben Cherry's famous article "JavaScript Module Pattern: In-Depth".

7. Module specifications

Think about it first, why are modules important?

 Because of the modules, we can use other people’s code more conveniently, and load whatever modules we want for whatever functions we want.

 However, there is a prerequisite for doing this, that is, everyone must write the module in the same way, otherwise you have your way of writing, and I have my way of writing, wouldn’t it be a mess! This is even more important considering that there is no official specification for Javascript modules yet.

  目前,通行的 Javascript 模块规范共有两种:CommonJS 和 AMD。我主要介绍 AMD,但是要先从 CommonJS 讲起。

八、CommonJS

  2009年,美国程序员 Ryan Dahl 创造了 node.js 项目,将 Javascript 语言用于服务器端编程。

  这标志"Javascript 模块化编程"正式诞生。因为老实说,在浏览器环境下,没有模块也不是特别大的问题,毕竟网页程序的复杂性有限;但是在服务器端,一定要有模块,与操作系统和其他应用程序互动,否则根本没法编程。

  node.js 的模块系统,就是参照 CommonJS 规范实现的。在 CommonJS 中,有一个全局性方法 require (),用于加载模块。假定有一个数学模块 math.js,就可以像下面这样加载。

var math = require ('math'); 

  然后,就可以调用模块提供的方法:

var math = require ('math');
math.add (2,3); // 5 

  因为这个系列主要针对浏览器编程,不涉及 node.js,所以对 CommonJS 就不多做介绍了。我们在这里只要知道,require () 用于加载模块就行了。

九、浏览器环境

  有了服务器端模块以后,很自然地,大家就想要客户端模块。而且最好两者能够兼容,一个模块不用修改,在服务器和浏览器都可以运行。

  但是,由于一个重大的局限,使得 CommonJS 规范不适用于浏览器环境。还是上一节的代码,如果在浏览器中运行,会有一个很大的问题,你能看出来吗?

var math = require ('math');
math.add (2, 3); 

  第二行 Math.add (2, 3),在第一行 require ('math') 之后运行,因此必须等 math.js 加载完成。也就是说,如果加载时间很长,整个应用就会停在那里等。

  这对服务器端不是一个问题,因为所有的模块都存放在本地硬盘,可以同步加载完成,等待时间就是硬盘的读取时间。但是,对于浏览器,这却是一个大问题,因为模块都放在服务器端,等待时间取决于网速的快慢,可能要等很长时间,浏览器处于"假死"状态。

  因此,浏览器端的模块,不能采用"同步加载"(synchronous),只能采用"异步加载"(asynchronous)。这就是 AMD 规范诞生的背景。

十、AMD

  AMD 是"Asynchronous Module Definition"的缩写,意思就是"异步模块定义"。它采用异步方式加载模块,模块的加载不影响它后面语句的运行。所有依赖这个模块的语句,都定义在一个回调函数中,等到加载完成之后,这个回调函数才会运行。

  AMD 也采用 require ()语句加载模块,但是不同于 CommonJS,它要求两个参数:

require ([module], callback); 

  第一个参数[module],是一个数组,里面的成员就是要加载的模块;第二个参数 callback,则是加载成功之后的回调函数。如果将前面的代码改写成 AMD 形式,就是下面这样:

require (['math'], function (math) {
    math.add (2, 3);
}); 

  math.add () 与 math 模块加载不是同步的,浏览器不会发生假死。所以很显然,AMD 比较适合浏览器环境。

  目前,主要有两个 Javascript 库实现了 AMD 规范:require.js 和 curl.js。本系列的第三部分,将通过介绍 require.js,进一步讲解 AMD 的用法,以及如何将模块化编程投入实战。

  我采用的是一个非常流行的库 require.js。

一、为什么要用 require.js?

  最早的时候,所有 Javascript 代码都写在一个文件里面,只要加载这一个文件就够了。后来,代码越来越多,一个文件不够了,必须分成多个文件,依次加载。下面的网页代码,相信很多人都见过。

<script src="1.js"></script>
<script src="2.js"></script>
<script src="3.js"></script>
<script src="4.js"></script>
<script src="5.js"></script>
<script src="6.js"></script>

  这段代码依次加载多个 js 文件。

  这样的写法有很大的缺点。首先,加载的时候,浏览器会停止网页渲染,加载文件越多,网页失去响应的时间就会越长;其次,由于 js 文件之间存在依赖关系,因此必须严格保证加载顺序(比如上例的1.js 要在2.js 的前面),依赖性最大的模块一定要放到最后加载,当依赖关系很复杂的时候,代码的编写和维护都会变得困难。

  require.js 的诞生,就是为了解决这两个问题:

(1)实现 js 文件的异步加载,避免网页失去响应;

(2)管理模块之间的依赖性,便于代码的编写和维护。

二、require.js 的加载

  使用 require.js 的第一步,是先去官方网站下载最新版本。

  下载后,假定把它放在 js 子目录下面,就可以加载了。

<script src="js/require.js"></script>

  有人可能会想到,加载这个文件,也可能造成网页失去响应。解决办法有两个,一个是把它放在网页底部加载,另一个是写成下面这样:

<script src="js/require.js" defer async="true"></script>

  async 属性表明这个文件需要异步加载,避免网页失去响应。IE 不支持这个属性,只支持 defer,所以把 defer 也写上。

  加载 require.js 以后,下一步就要加载我们自己的代码了。假定我们自己的代码文件是 main.js,也放在 js 目录下面。那么,只需要写成下面这样就行了:

<script src="js/require.js" data-main="js/main"></script>

  data-main 属性的作用是,指定网页程序的主模块。在上例中,就是 js 目录下面的 main.js,这个文件会第一个被 require.js 加载。由于 require.js 默认的文件后缀名是 js,所以可以把 main.js 简写成 main。

三、主模块的写法

  上一节的 main.js,我把它称为"主模块",意思是整个网页的入口代码。它有点像C语言的 main ()函数,所有代码都从这儿开始运行。

  下面就来看,怎么写 main.js。

  如果我们的代码不依赖任何其他模块,那么可以直接写入 javascript 代码。

// main.js
alert ("加载成功!");

  但这样的话,就没必要使用 require.js 了。真正常见的情况是,主模块依赖于其他模块,这时就要使用 AMD 规范定义的的 require ()函数。

// main.js
require (['moduleA', 'moduleB', 'moduleC'], function (moduleA, moduleB, moduleC){
// some code here
});

  require () 函数接受两个参数。第一个参数是一个数组,表示所依赖的模块,上例就是['moduleA', 'moduleB', 'moduleC'],即主模块依赖这三个模块;第二个参数是一个回调函数,当前面指定的模块都加载成功后,它将被调用。加载的模块会以参数形式传入该函数,从而在回调函数内部就可以使用这些模块。

  require () 异步加载 moduleA,moduleB 和 moduleC,浏览器不会失去响应;它指定的回调函数,只有前面的模块都加载成功后,才会运行,解决了依赖性的问题。

  下面,我们看一个实际的例子。

  假定主模块依赖 jquery、underscore 和 backbone 这三个模块,main.js 就可以这样写:

require (['jquery', 'underscore', 'backbone'], function ($, _, Backbone){
// some code here
});

  require.js 会先加载 jQuery、underscore 和 backbone,然后再运行回调函数。主模块的代码就写在回调函数中。

四、模块的加载

  上一节最后的示例中,主模块的依赖模块是['jquery', 'underscore', 'backbone']。默认情况下,require.js 假定这三个模块与 main.js 在同一个目录,文件名分别为 jquery.js,underscore.js 和 backbone.js,然后自动加载。

  使用 require.config () 方法,我们可以对模块的加载行为进行自定义。require.config () 就写在主模块(main.js)的头部。参数就是一个对象,这个对象的 paths 属性指定各个模块的加载路径。

require.config ({
    paths: {
        "jquery": "jquery.min.js",
        "underscore": "underscore.min.js",
        "backbone": "backbone.min.js"
    }
});

  上面的代码给出了三个模块的文件名,路径默认与 main.js 在同一个目录(js 子目录)。如果这些模块在其他目录,比如 js/lib 目录,则有两种写法。一种是逐一指定路径。

require.config ({
    paths: {
        "jquery": "lib/jquery.min.js",
        "underscore": "lib/underscore.min.js",
        "backbone": "lib/backbone.min.js"
    }
}); 

  另一种则是直接改变基目录(baseUrl)。

require.config ({
    baseUrl: "js/lib",
    paths: {
        "jquery": "jquery.min.js",
        "underscore": "underscore.min.js",
        "backbone": "backbone.min.js"
    }
});

  如果某个模块在另一台主机上,也可以直接指定它的网址,比如:

require.config ({
    paths: {
        "jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min"
    }
});

  require.js 要求,每个模块是一个单独的 js 文件。这样的话,如果加载多个模块,就会发出多次 HTTP 请求,会影响网页的加载速度。因此,require.js 提供了一个优化工具,当模块部署完毕以后,可以用这个工具将多个模块合并在一个文件中,减少 HTTP 请求数。

五、AMD 模块的写法

  require.js 加载的模块,采用 AMD 规范。也就是说,模块必须按照 AMD 的规定来写。

  具体来说,就是模块必须采用特定的 define () 函数来定义。如果一个模块不依赖其他模块,那么可以直接定义在 define () 函数之中。

  假定现在有一个 math.js 文件,它定义了一个 math 模块。那么,math.js 就要这样写:

// math.js
define(function () {
    var add = function (x, y) {
        return x + y;
    };
    return {
        add: add
    };
});

  加载方法如下:

// main.js
require(['math'], function (math) {
    alert(math.add(1, 1));
});

  如果这个模块还依赖其他模块,那么 define ()函数的第一个参数,必须是一个数组,指明该模块的依赖性。

define(['myLib'], function (myLib) {
    function foo() {
        myLib.doSomething();
    }
    return {
        foo: foo
    };
});

  当 require ()函数加载上面这个模块的时候,就会先加载 myLib.js 文件。

六、加载非规范的模块

  理论上,require.js 加载的模块,必须是按照 AMD 规范、用 define () 函数定义的模块。但是实际上,虽然已经有一部分流行的函数库(比如 jQuery)符合 AMD 规范,更多的库并不符合。那么,require.js 是否能够加载非规范的模块呢?

  回答是可以的。

  这样的模块在用 require () 加载之前,要先用 require.config ()方法,定义它们的一些特征。

  举例来说,underscore 和 backbone 这两个库,都没有采用 AMD 规范编写。如果要加载它们的话,必须先定义它们的特征。

require.config({
    shim: {
        'underscore': {
            exports: '_'
        },
        'backbone': {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        }
    }
});

  require.config () 接受一个配置对象,这个对象除了有前面说过的 paths 属性之外,还有一个 shim 属性,专门用来配置不兼容的模块。具体来说,每个模块要定义(1)exports 值(输出的变量名),表明这个模块外部调用时的名称;(2)deps 数组,表明该模块的依赖性。

  比如,jQuery 的插件可以这样定义:

shim: {
    'jquery.scroll': {
        deps: ['jquery'],
        exports: 'jQuery.fn.scroll'
    }
}

七、require.js 插件

  require.js 还提供一系列插件,实现一些特定的功能。

  domready 插件,可以让回调函数在页面 DOM 结构加载完成后再运行。

require(['domready!'], function (doc) {
    // called once the DOM is ready
});

  text 和 image 插件,则是允许 require.js 加载文本和图片文件。

define([
    'text!review.txt',
    'image!cat.jpg'
    ],
    function (review, cat) {
        console.log(review);
        document.body.appendChild(cat);
    }
);

  类似的插件还有 json 和 mdown,用于加载 json 文件和 markdown 文件。

以上就介绍了javascript模块化编程转载,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

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
vue3+vite:src使用require动态导入图片报错怎么解决vue3+vite:src使用require动态导入图片报错怎么解决May 21, 2023 pm 03:16 PM

vue3+vite:src使用require动态导入图片报错和解决方法vue3+vite动态的导入多张图片vue3如果使用的是typescript开发,就会出现require引入图片报错,requireisnotdefined不能像使用vue2这样imgUrl:require(&rsquo;&hellip;/assets/test.png&rsquo;)导入,是因为typescript不支持require所以用import导入,下面介绍如何解决:使用awaitimport

js字符串转数组js字符串转数组Aug 03, 2023 pm 01:34 PM

js字符串转数组的方法:1、使用“split()”方法,可以根据指定的分隔符将字符串分割成数组元素;2、使用“Array.from()”方法,可以将可迭代对象或类数组对象转换成真正的数组;3、使用for循环遍历,将每个字符依次添加到数组中;4、使用“Array.split()”方法,通过调用“Array.prototype.forEach()”将一个字符串拆分成数组的快捷方式。

js中new操作符做了哪些事情js中new操作符做了哪些事情Nov 13, 2023 pm 04:05 PM

js中new操作符做了:1、创建一个空对象,这个新对象将成为函数的实例;2、将新对象的原型链接到构造函数的原型对象,这样新对象就可以访问构造函数原型对象中定义的属性和方法;3、将构造函数的作用域赋给新对象,这样新对象就可以通过this关键字来引用构造函数中的属性和方法;4、执行构造函数中的代码,构造函数中的代码将用于初始化新对象的属性和方法;5、如果构造函数中没有返回等等。

require的用法有哪些require的用法有哪些Nov 27, 2023 am 10:03 AM

require用法:1、引入模块:在许多编程语言中,require用于引入外部模块或库,以便在程序中使用它们提供的功能。例如,在Ruby中,可以使用require来加载第三方库或模块;2、导入类或方法:在一些编程语言中,require用于导入特定的类或方法,以便在当前文件中使用它们;3、执行特定任务:在一些编程语言或框架中,require用于执行特定的任务或功能。

用JavaScript模拟实现打字小游戏!用JavaScript模拟实现打字小游戏!Aug 07, 2022 am 10:34 AM

这篇文章主要为大家详细介绍了js实现打字小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

php可以读js内部的数组吗php可以读js内部的数组吗Jul 12, 2023 pm 03:41 PM

php在特定情况下可以读js内部的数组。其方法是:1、在JavaScript中,创建一个包含需要传递给PHP的数组的变量;2、使用Ajax技术将该数组发送给PHP脚本。可以使用原生的JavaScript代码或者使用基于Ajax的JavaScript库如jQuery等;3、在PHP脚本中,接收传递过来的数组数据,并进行相应的处理即可。

js是什么编程语言?js是什么编程语言?May 05, 2019 am 10:22 AM

js全称JavaScript,是一种具有函数优先的轻量级,直译式、解释型或即时编译型的高级编程语言,是一种属于网络的高级脚本语言;JavaScript基于原型编程、多范式的动态脚本语言,并且支持面向对象、命令式和声明式,如函数式编程。

js原生选择器有哪些js原生选择器有哪些Oct 16, 2023 pm 03:42 PM

js原生选择器有getElementById()、getElementsByClassName()、getElementsByTagName()、querySelector()和querySelectorAll()等。详细介绍:1、getElementById()通过元素的唯一标识符来选择元素,它返回具有指定ID的元素作为结果等等。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools