Home Web Front-end JS Tutorial Deep copy of objects in JavaScript

Deep copy of objects in JavaScript

Jan 03, 2017 pm 03:49 PM
Modular development

What is modular development?

In front-end development, at first, some basic interactive effects could be achieved by embedding dozens or hundreds of lines of code in script tags. Later, js gained attention and was widely used, including jQuery, Ajax, and Node.Js. , MVC, MVVM, etc. have also brought attention to front-end development and made front-end projects more and more complex. However, JavaScript does not provide any obvious help in organizing code, and there is not even the concept of classes, let alone modules. , so what is a module?

A module is a file that implements a specific function. With a module, we can use other people's code more conveniently, and load whatever module we want for whatever function we want. Module development needs to follow certain standards, otherwise everything will be messed up.

According to AMD specifications, we can use define to define modules and require to call modules.

Currently, there are two main popular js module specifications: CommonJS and AMD.

AMD specification

AMD is Asynchronous Module Definition, and the Chinese name means "asynchronous module definition". It is a specification for modular development on the browser side. The specification on the server side is that CommonJS

modules will be loaded asynchronously, and module loading will not affect the running of subsequent statements. All statements that depend on certain modules are placed in callback functions.

AMD is the standardized output of module definitions during the promotion process of RequireJS.

define() function

AMD specification only defines one function define, which is a global variable. The description of the function is:

define(id?, dependencies?, factory);
Copy after login

Parameter description:

id: refers to the name of the module in the definition, optional; if this parameter is not provided , the module name should default to the name of the specified script requested by the module loader. If this parameter is provided, the module name must be "top-level" and absolute (relative names are not allowed).

Dependencies dependencies: It is an array literal of the module identifier that the current module depends on and has been defined by the module.
The dependency parameter is optional, if this parameter is omitted, it should default to ["require", "exports", "module"]. However, if the factory method's length attribute is less than 3, the loader will choose to call the factory method with the number of arguments specified by the function's length attribute.

Factory method factory, the module initializes the function or object to be executed. If it is a function, it should be executed only once. If it is an object, this object should be the output value of the module.

Format of module name

Module names are used to uniquely identify the modules in the definition. They are also used in the dependency array:

Module names are separated by forward slashes A string of meaningful words
Words must be in camel case, or ".", ".."
The module name does not allow file extensions, such as ".js"
The module name can be " Relative" or "top level". If the first character is "." or "..", it is a relative module name
The top-level module name is resolved from the conceptual module of the root namespace
The relative module name is resolved from the "require" written and called module

Use require and exports

Create a module named "alpha", use require, exports, and a module named "beta":

define("alpha", ["require", "exports", "beta"], function (require, exports, beta) {
   exports.verb = function() {
     return beta.verb();
     //Or:
     return require("beta").verb();
   }
 });
Copy after login

require API introduction: https://github.com/amdjs/amdjs-api/wiki/require

AMD specification Chinese version: https://github.com/ amdjs/amdjs-api/wiki/AMD-(%E4%B8%AD%E6%96%87%E7%89%88)

Currently, libraries that implement AMD include RequireJS, curl, Dojo, and Nodules wait.

CommonJS specification

CommonJS is a specification for server-side modules, and Node.js adopts this specification. Node.JS first adopted the concept of js modularity.

According to the CommonJS specification, a single file is a module. Each module has a separate scope, that is to say, variables defined within the module cannot be read by other modules unless they are defined as attributes of the global object.

The best way to export module variables is to use the module.exports object.

var i = 1;
var max = 30;
 
module.exports = function () {
 for (i -= 1; i++ < max; ) {
  console.log(i);
 }
 max *= 1.1;
};
Copy after login

The above code defines a function through the module.exports object, which is the bridge between the external and internal communication of the module.

Load the module using the require method, which reads a file and executes it, and finally returns the module.exports object inside the file.

CommonJS specification: http://javascript.ruanyifeng.com/nodejs/commonjs.html

RequireJS and SeaJS

RequireJS was created by James Burke, who is also the AMD specification Founder.

The define method is used to define modules. RequireJS requires each module to be placed in a separate file.

RequireJS and Sea.js are both module loaders, advocating the concept of modular development, and their core value is to make modular development of JavaScript simple and natural.

The biggest difference between SeaJS and RequireJS:

SeaJS’s attitude towards modules is lazy execution, while RequireJS’s attitude towards modules is pre-execution

Don’t understand? Take a look at this article with pictures and text: http://www.douban.com/note/283566440/

RequireJS API:http://www.requirejs.cn/docs/api.html

RequireJS usage: http://www.ruanyifeng.com/blog/2012/11/require_js.html

Why use requireJS

试想一下,如果一个网页有很多的js文件,那么浏览器在下载该页面的时候会先加载js文件,从而停止了网页的渲染,如果文件越多,浏览器可能失去响应。其次,要保证js文件的依赖性,依赖性最大的模块(文件)要放在最后加载,当依赖关系很复杂的时候,代码的编写和维护都会变得困难。

RequireJS就是为了解决这两个问题而诞生的:

(1)实现js文件的异步加载,避免网页失去响应;
(2)管理模块之间的依赖性,便于代码的编写和维护。

RequireJS文件下载:http://www.requirejs.cn/docs/download.html

AMD和CMD

CMD(Common Module Definition) 通用模块定义。该规范明确了模块的基本书写格式和基本交互规则。该规范是在国内发展出来的。AMD是依赖关系前置,CMD是按需加载。

在 CMD 规范中,一个模块就是一个文件。代码的书写格式如下:

define(factory);
Copy after login

factory 为函数时,表示是模块的构造方法。执行该构造方法,可以得到模块向外提供的接口。factory 方法在执行时,默认会传入三个参数:require、exports 和 module:

define(function(require, exports, module) {
 // 模块代码
});
Copy after login

require是可以把其他模块导入进来的一个参数,而export是可以把模块内的一些属性和方法导出的。

CMD规范地址:https://github.com/seajs/seajs/issues/242

AMD 是 RequireJS 在推广过程中对模块定义的规范化产出。
CMD 是 SeaJS 在推广过程中对模块定义的规范化产出。

对于依赖的模块,AMD 是提前执行,CMD 是延迟执行。

AMD:提前执行(异步加载:依赖先执行)+延迟执行
CMD:延迟执行(运行到需加载,根据顺序执行)
CMD 推崇依赖就近,AMD 推崇依赖前置。看如下代码:

// CMD
define(function(require, exports, module) {
var a = require(&#39;./a&#39;)
a.doSomething()
// 此处略去 100 行
var b = require(&#39;./b&#39;) // 依赖可以就近书写
b.doSomething()
// ...
})
 
// AMD 默认推荐的是
define([&#39;./a&#39;, &#39;./b&#39;], function(a, b) { // 依赖必须一开始就写好
a.doSomething()
// 此处略去 100 行
b.doSomething()
...
})
Copy after login

另外一个区别是:

AMD:API根据使用范围有区别,但使用同一个api接口
CMD:每个API的职责单一
AMD的优点是:异步并行加载,在AMD的规范下,同时异步加载是不会产生错误的。
CMD的机制则不同,这种加载方式会产生错误,如果能规范化模块内容形式,也可以

jquery1.7以上版本会自动模块化,支持AMD模式:主要是使用define函数,sea.js虽然是CommonJS规范,但却使用了define来定义模块
所以jQuery已经自动模块化了

seajs.config({
&#39;base&#39;:&#39;/&#39;,
&#39;alias&#39;:{
  &#39;jquery&#39;:&#39;jquery.js&#39;//定义jQuery文件
}
});
Copy after login

define函数和AMD的define类似:

define(function(require, exports, module{
   //先要载入jQuery的模块
   var $ = require(&#39;jquery&#39;);
   //然后将jQuery对象传给插件模块
   require(&#39;./cookie&#39;)($);
   //开始使用 $.cookie方法
});
Copy after login

sea.js如何使用?

引入sea.js的库

如何变成模块?

define

3.如何调用模块?

-exports
-sea.js.use
4.如何依赖模块?

-require

<script type="text/javascript">
    define(function (require,exports,module) {
      //exports : 对外的接口
      //requires : 依赖的接口
      require(&#39;./test.js&#39;);//如果地址是一个模块的话,那么require的返回值就是模块中的exports
    })
</script>
Copy after login

sea.js 开发实例

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>鼠标拖拽的模块化开发实践</title>
<style type="text/css">
#div1{ width:200px; height:200px; background:black; position:absolute; display:none;}
#div2{ width:30px; height:30px; background:yellow; position:absolute; bottom:0; right:0;}
#div3{ width:100px; height:100px; background:blue; position:absolute; right:0; top:0;}
</style>
<script type="text/javascript" src="./sea.js"></script>
<script type="text/javascript">
   
//A同事 :
seajs.use(&#39;./main.js&#39;);
   
</script>
</head>
 
<body>
<input type="button" value="确定" id="input1" />
<div id="div1">
  <div id="div2"></div>
</div>
<div id="div3"></div>
</body>
</html>
Copy after login

A同事

//A同事写的main.js:
 
define(function (require,exports,module) {
  var oInput = document.getElementById(&#39;input1&#39;);
  var oDiv1 = document.getElementById(&#39;div1&#39;);
  var oDiv2 = document.getElementById(&#39;div2&#39;);
  var oDiv3 = document.getElementById(&#39;div3&#39;);
 
  require(&#39;./drag.js&#39;).drag(oDiv3);
  oInput.onclick = function () {
    oDiv1.style.display = &#39;block&#39;;
    require(&#39;./scale.js&#39;).scale(oDiv1,oDiv2);
 
    require.async(&#39;./scale.js&#39;, function (ex) {
      ex.scale(oDiv1,oDiv2);
    })
  }
});
Copy after login

B同事

//B同事写的drag.js:
 
define(function(require,exports,module){
   
  function drag(obj){
    var disX = 0;
    var disY = 0;
    obj.onmousedown = function(ev){
      var ev = ev || window.event;
      disX = ev.clientX - obj.offsetLeft;
      disY = ev.clientY - obj.offsetTop;
       
      document.onmousemove = function(ev){
        var ev = ev || window.event;
 
 
         var L = require(&#39;./range.js&#39;).range(ev.clientX - disX , document.documentElement.clientWidth - obj.offsetWidth , 0 );
         var T = require(&#39;./range.js&#39;).range(ev.clientY - disY , document.documentElement.clientHeight - obj.offsetHeight , 0 );
 
         
        obj.style.left = L + &#39;px&#39;;
        obj.style.top = T + &#39;px&#39;;
      };
      document.onmouseup = function(){
        document.onmousemove = null;
        document.onmouseup = null;
      };
      return false;
    };
  }
   
  exports.drag = drag;//对外提供接口
   
});
Copy after login

C同事

//C同事写的scale.js:
 
define(function(require,exports,module){
   
   
  function scale(obj1,obj2){
    var disX = 0;
    var disY = 0;
    var disW = 0;
    var disH = 0;
     
    obj2.onmousedown = function(ev){
      var ev = ev || window.event;
      disX = ev.clientX;
      disY = ev.clientY;
      disW = obj1.offsetWidth;
      disH = obj1.offsetHeight;
       
      document.onmousemove = function(ev){
        var ev = ev || window.event;
         
        var W = require(&#39;./range.js&#39;).range(ev.clientX - disX + disW , 500 , 100);
        var H = require(&#39;./range.js&#39;).range(ev.clientY - disY + disH , 500 , 100);
         
        obj1.style.width = W + &#39;px&#39;;
        obj1.style.height = H + &#39;px&#39;;
      };
      document.onmouseup = function(){
        document.onmousemove = null;
        document.onmouseup = null;
      };
      return false;
    };
     
  }
   
  exports.scale = scale;
   
});
Copy after login

D同事

// D同事的range.js--限定拖拽范围
 
  define(function(require,exports,module){
     
    function range(iNum,iMax,iMin){
       
      if( iNum > iMax ){
        return iMax;
      }
      else if( iNum < iMin ){
        return iMin;
      }
      else{
        return iNum;
      }
       
    }
     
    exports.range = range;
     
  });
Copy after login

requirejs开发实例

require.config是用来定义别名的,在paths属性下配置别名。然后通过requirejs(参数一,参数二);参数一是数组,传入我们需要引用的模块名,第二个参数是个回调函数,回调函数传入一个变量,代替刚才所引入的模块。

main.js文件

//别名配置
requirejs.config({
  paths: {
    jquery: &#39;jquery.min&#39; //可以省略.js
  }
});
//引入模块,用变量$表示jquery模块
requirejs([&#39;jquery&#39;], function ($) {
  $(&#39;body&#39;).css(&#39;background-color&#39;,&#39;red&#39;);
});
Copy after login

引入模块也可以只写require()。requirejs通过define()定义模块,定义的参数上同。在此模块内的方法和变量外部是无法访问的,只有通过return返回才行.

define 模块

define([&#39;jquery&#39;], function ($) {//引入jQuery模块
  return {
    add: function(x,y){
      return x + y;
    }
  };
});
Copy after login

将该模块命名为math.js保存。

main.js引入模块方法

require([&#39;jquery&#39;,&#39;math&#39;], function ($,math) {
  console.log(math.add(10,100));//110
});
Copy after login

没有依赖

如果定义的模块不依赖其他模块,则可以:

define(function () {
 
  return {
    name: "trigkit4",
    age: "21"
  }
});
Copy after login

   

AMD推荐的风格通过返回一个对象做为模块对象,CommonJS的风格通过对module.exports或exports的属性赋值来达到暴露模块对象的目的。

更多JavaScript 中对象的深拷贝相关文章请关注PHP中文网!

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
How to use PHP and webpack for modular development How to use PHP and webpack for modular development May 11, 2023 pm 03:52 PM

With the continuous development of web development technology, front-end and back-end separation and modular development have become a widespread trend. PHP is a commonly used back-end language. When doing modular development, we need to use some tools to manage and package modules. Webpack is a very easy-to-use modular packaging tool. This article will introduce how to use PHP and webpack for modular development. 1. What is modular development? Modular development refers to decomposing a program into different independent modules. Each module has its own function.

PHP study notes: modular development and code reuse PHP study notes: modular development and code reuse Oct 10, 2023 pm 12:58 PM

PHP study notes: Modular development and code reuse Introduction: In software development, modular development and code reuse are very important concepts. Modular development can decompose complex systems into manageable small modules, improving development efficiency and code maintainability; while code reuse can reduce redundant code and improve code reusability. In PHP development, we can achieve modular development and code reuse through some technical means. This article will introduce some commonly used technologies and specific code examples to help readers better understand and apply these concepts.

C++ development advice: How to carry out modular C++ development C++ development advice: How to carry out modular C++ development Nov 23, 2023 am 08:56 AM

C++ language, as a general-purpose high-level programming language, is widely used to develop various applications and systems. However, the complexity and flexibility of C++ also make developers face some challenges, especially in large projects. When dealing with large projects, a modular development approach is crucial. This article will introduce how to do modular C++ development and provide some suggestions and best practices. Modular development refers to dividing a large project into multiple small modules. Each module has its own functions and responsibilities, and communicates through the interface between modules.

ThinkPHP6 modular development: dismantling application logic ThinkPHP6 modular development: dismantling application logic Aug 12, 2023 am 10:53 AM

ThinkPHP6 modular development: dismantling application logic With the rapid development of the Internet, Web application development has become more and more complex. A large application may contain multiple modules, each module is responsible for different functions, and disassembling application logic becomes an issue that must be considered. This article will introduce how to implement modular development in ThinkPHP6 and use code examples to help readers understand. 1. Create modules. In ThinkPHP6, modules are divisions of application functions. Different modules can be created according to actual needs.

Technical guide for implementing modular development of Python scripts in Linux systems Technical guide for implementing modular development of Python scripts in Linux systems Oct 05, 2023 am 11:53 AM

Technical Guide for Implementing Modular Development of Python Scripts in Linux Systems Introduction: Python is an easy-to-learn and powerful high-level programming language that is widely used in development in different fields. In Linux systems, modular development of Python scripts can effectively improve the maintainability and reusability of code and reduce development and maintenance costs. This article will introduce technical guidelines on how to use Python to implement modular development in Linux systems, and provide specific code examples. 1. Modularization

Vue development suggestions: How to carry out modular development and component reuse Vue development suggestions: How to carry out modular development and component reuse Nov 22, 2023 am 09:51 AM

Vue is a popular JavaScript framework for building user interfaces. It adopts a component-based development approach, allowing developers to easily carry out modular development and component reuse. This article will introduce some Vue development suggestions on how to implement modular development and component reuse. 1. Modular development Modular development is a method of disassembling a complex system into several independent modules, each module is responsible for completing a specific function. In Vue, we can use Vue components to achieve modular development. Here is some information about the module

How to implement modular development of PHP functions under microservice architecture? How to implement modular development of PHP functions under microservice architecture? Sep 18, 2023 pm 01:31 PM

How to implement modular development of PHP functions under microservice architecture? As technology continues to evolve, microservice architecture is becoming more and more popular in software development. It splits a large application into many small, independent functional modules, each of which can be developed, deployed, and expanded independently. For PHP developers, how to use microservice architecture to achieve modular development of functions is an important topic. In this article, we will introduce some technologies and best practices to achieve modular development of PHP functions under a microservice architecture. first

Spring Boot's modular development and application scenarios Spring Boot's modular development and application scenarios Jun 23, 2023 am 09:16 AM

When we talk about SpringBoot, we usually think of a rapid development framework. However, its benefits don’t stop there. Another great feature of SpringBoot is that it supports modular development, which makes development easier and easier to maintain. In this article, we will explore the basics of SpringBoot modular development and how to use this feature in practical applications. What is a SpringBoot module? SpringBoot module is a set of functional

See all articles