Home > Web Front-end > JS Tutorial > body text

Deep copy of objects in JavaScript

高洛峰
Release: 2017-01-03 15:49:03
Original
1480 people have browsed it

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中文网!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!