您的位置:首页 > Web前端 > Node.js

Node.js 中的copy

2015-10-10 12:38 471 查看


想在node中复制对象,搜了下 node util 中的_extend 可以。

在试验过程中,对浅复制有了更深一层的理解。


直接上代码吧,看具体是怎样的。

var extend = require('util')._extend;

var obj1 = {x: 5, y:5};
var obj2 = extend({}, obj1);

obj2.x = 6;

console.log("The obj1.x is " + obj1.x);
console.log("The obj2.x is " + obj2.x);

obj1.x 会不会变? 不会,还是5。
obj2.x 会不会被改?  是的,被改成了6。


那我们再来改动下代码,看有什么变化。

var extend = require('util')._extend;

var obj1 = {x: 5, y:5, z: {value: 5}};
var obj2 = extend({}, obj1);

obj2.z.value =6;

console.log("the value of obj1.z.value is " + obj1.z.value);
console.log("the value of obj2.z.value is " + obj2.z.value);

再看一下,obj1.z.value 和obj2.z.value 都变成了6。


为什么呢?

_extend属于浅复制,让我们看一下浅复制到底复制些什么。


Wiki上是这么定义的:

One method of copying an object is the shallow copy. In that case a new object B is created, and the fields values of A are copied over to B.[3][4][5][6] If the field value is a reference to an object (e.g., a memory address) it copies the reference, hence referring to the same object as A does, and if the field value is a primitive type it copies the value of the primitive type.


可以看出来,对于primitive type, 值会被复制。 而第一个实例中的obj2.x 是number类型,所以值也被复制了,而obj1.x的值不受影响。


对于object, 对象来讲, 只是把对象的引用(reference)复制了。 也就是说两个引用其实指的还是同一个对象。所以obj2.z.value的值被改动后,obj1和obj2 指向的相同对象被更改了,所以都打印出更改后的值。


另,

1. 在stackoverflow 中有对shallow copy 和deep copy 的比较

2. node中 还可以用如下方式进行对象复制。

var obj2 = JSON.parse(JSON.stringify(obj1));





  


  



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: