在Node.js中克隆一个对象

时间:2021-09-21 22:02:40

What is the best way to clone an object in node.js

在node.js中克隆一个对象的最佳方法是什么?

e.g. I want to avoid the situation where:

我想避免这种情况:

var obj1 = {x: 5, y:5};
var obj2 = obj1;
obj2.x = 6;
console.log(obj1.x); // logs 6

The object may well contain complex types as attributes, so a simple for(var x in obj1) wouldn't solve. Do I need to write a recursive clone myself or is there something built in that I'm not seeing?

对象很可能包含复杂类型作为属性,因此简单的for(obj1中的var x)不能解决这个问题。我需要自己写一个递归克隆吗,还是有什么我看不到的东西?

18 个解决方案

#1


253  

Possibility 1

Low-frills deep copy:

Low-frills深拷贝:

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

Possibility 2 (deprecated)

Attention: This solution is now marked as deprecated in the documentation of Node.js:

注意:这个解决方案现在在Node.js的文档中被标记为不赞成:

The util._extend() method was never intended to be used outside of internal Node.js modules. The community found and used it anyway.

不打算在内部节点外部使用util._extend()方法。js模块。社区找到并使用了它。

It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign().

它已被弃用,不应在新代码中使用。JavaScript通过Object.assign()提供了非常类似的内置功能。

Original answer::

原来的答案::

For a shallow copy, use Node's built-in util._extend() function.

对于浅拷贝,使用Node的内置util._extend()函数。

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

var obj1 = {x: 5, y:5};
var obj2 = extend({}, obj1);
obj2.x = 6;
console.log(obj1.x); // still logs 5

Source code of Node's _extend function is in here: https://github.com/joyent/node/blob/master/lib/util.js

Node的_extend函数的源代码在这里:https://github.com/joyent/node/blob/master/lib/util.js

exports._extend = function(origin, add) {
  // Don't do anything if add isn't an object
  if (!add || typeof add !== 'object') return origin;

  var keys = Object.keys(add);
  var i = keys.length;
  while (i--) {
    origin[keys[i]] = add[keys[i]];
  }
  return origin;
};

#2


165  

I'm surprised Object.assign hasn't been mentioned.

我很惊讶对象。分配还没有提到。

let cloned = Object.assign({}, source);

If available (e.g. Babel), you can use the object spread operator:

如果有的话(例如,Babel),你可以使用对象扩展运算符:

let cloned = { ... source };

#3


23  

Object.defineProperty(Object.prototype, "extend", {
    enumerable: false,
    value: function(from) {
        var props = Object.getOwnPropertyNames(from);
        var dest = this;
        props.forEach(function(name) {
            if (name in dest) {
                var destination = Object.getOwnPropertyDescriptor(from, name);
                Object.defineProperty(dest, name, destination);
            }
        });
        return this;
    }
});

This will define an extend method that you can use. Code comes from this article.

这将定义一个扩展方法,您可以使用它。代码来自本文。

#4


16  

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

#5


13  

You can use the extend function from JQuery:

您可以使用JQuery的扩展函数:

var newClone= jQuery.extend({}, oldObject);  
var deepClone = jQuery.extend(true, {}, oldObject); 

There is a Node.js Plugin too:

有一个节点。js插件:

https://github.com/shimondoodkin/nodejs-clone-extend

https://github.com/shimondoodkin/nodejs-clone-extend

To do it without JQuery or Plugin read this here:

在没有JQuery或插件的情况下,请阅读以下内容:

http://my.opera.com/GreyWyvern/blog/show.dml/1725165

http://my.opera.com/GreyWyvern/blog/show.dml/1725165

#6


12  

Check out underscore.js. It has both clone and extend and many other very useful functions.

查看underscore.js。它具有克隆和扩展以及许多其他非常有用的功能。

This can be useful: Using the Underscore module with Node.js

这可能很有用:使用带有Node.js的下划线模块

#7


8  

There are some Node modules out there if don't want to "roll your own". This one looks good: https://www.npmjs.com/package/clone

如果不想“滚你自己的”,还有一些节点模块。这个看起来不错:https://www.npmjs.com/package/clone

Looks like it handles all kinds of stuff, including circular references. From the github page:

看起来它可以处理各种各样的东西,包括循环引用。从github页面:

clone masters cloning objects, arrays, Date objects, and RegEx objects. Everything is cloned recursively, so that you can clone dates in arrays in objects, for example. [...] Circular references? Yep!

克隆控制克隆对象、数组、日期对象和RegEx对象。所有东西都被递归地克隆,因此您可以在对象的数组中克隆日期。[…循环引用吗?是的!

#8


6  

Simple and the fastest way to clone an Object in NodeJS is to use Object.keys( obj ) method

在node . js中克隆对象的最简单、最快的方法是使用Object。键(obj)方法

var a = {"a": "a11", "b": "avc"};
var b;

for(var keys = Object.keys(a), l = keys.length; l; --l)
{
   b[ keys[l-1] ] = a[ keys[l-1] ];
}
b.a = 0;

console.log("a: " + JSON.stringify(a)); // LOG: a: {"a":"a11","b":"avc"} 
console.log("b: " + JSON.stringify(b)); // LOG: b: {"a":0,"b":"avc"}

The method Object.keys requires JavaScript 1.8.5; nodeJS v0.4.11 supports this method

对象的方法。钥匙需要于JavaScript 1.8.5;nodeJS v0.4.11支持此方法

but of course for nested objects need to implement recursive func

但是,对于嵌套对象,当然需要实现递归函数。


Other solution is to use native JSON (Implemented in JavaScript 1.7), but it's much slower (~10 times slower) than previous one

其他的解决方案是使用本机JSON(在JavaScript 1.7中实现),但是它比以前的要慢很多(大约慢10倍)

var a = {"a": i, "b": i*i};
var b = JSON.parse(JSON.stringify(a));
b.a = 0;

#9


5  

There is also a project on Github that aims to be a more direct port of the jQuery.extend():

Github上还有一个项目,目的是成为jquery.org的一个更直接的端口。

https://github.com/dreamerslab/node.extend

https://github.com/dreamerslab/node.extend

An example, modified from the jQuery docs:

一个例子,修改自jQuery文档:

var extend = require('node.extend');

var object1 = {
    apple: 0,
    banana: {
        weight: 52,
        price: 100
    },
    cherry: 97
};

var object2 = {
    banana: {
        price: 200
    },
    durian: 100
};

var merged = extend(object1, object2);

#10


5  

This code is also work cause The Object.create() method creates a new object with the specified prototype object and properties.

由于object .create()方法使用指定的原型对象和属性创建一个新对象,所以这段代码也可以工作。

var obj1 = {x:5, y:5};

var obj2 = Object.create(obj1);

obj2.x; //5
obj2.x = 6;
obj2.x; //6

obj1.x; //5

#11


4  

There is another library lodash, it has clone and cloneDeep, also many other useful function.

还有一个库lodash,它有克隆和cloneDeep,还有许多其他有用的功能。

#12


3  

Looking for a true clone option, I stumbled across ridcully's link to here:

为了寻找一个真正的克隆选择,我偶然发现了ridcully的链接到这里:

http://my.opera.com/GreyWyvern/blog/show.dml/1725165

http://my.opera.com/GreyWyvern/blog/show.dml/1725165

I modified the solution on that page so that the function attached to the Object prototype is not enumerable. Here is my result:

我在该页上修改了解决方案,以使附加到对象原型的函数不具有可枚举性。这是我的结果:

Object.defineProperty(Object.prototype, 'clone', {
    enumerable: false,
    value: function() {
        var newObj = (this instanceof Array) ? [] : {};
        for (i in this) {
        if (i == 'clone') continue;
            if (this[i] && typeof this[i] == "object") {
                newObj[i] = this[i].clone();
            } else newObj[i] = this[i]
        } return newObj;
    }
});

Hopefully this helps someone else as well. Note that there are some caveats... particularly with properties named "clone". This works well for me. I don't take any credit for writing it. Again, I only changed how it was being defined.

希望这对其他人也有帮助。注意,有一些注意事项……尤其是那些名为“克隆”的属性。这对我很有效。我写这本书没有任何功劳。同样,我只是改变了它的定义。

#13


1  

You can also use SugarJS in NodeJS.

您也可以在NodeJS中使用SugarJS。

http://sugarjs.com/

http://sugarjs.com/

They have a very clean clone feature: http://sugarjs.com/api/Object/clone

他们有一个非常干净的克隆特性:http://sugarjs.com/api/Object/clone。

#14


0  

If you're using coffee-script, it's as easy as:

如果你使用的是咖啡脚本,那么这很简单:

newObject = {}
newObject[key] = value  for own key,value of oldObject

Though this isn't a deep clone.

虽然这不是一个深度克隆。

#15


0  

None of the answers satisfied me, several don't work or are just shallow clones, answers from @clint-harris and using JSON.parse/stringify are good but quite slow. I found a module that does deep cloning fast: https://github.com/AlexeyKupershtokh/node-v8-clone

这些答案中没有一个让我满意,有几个是无效的,或者只是简单的克隆。解析/stringify很好,但是很慢。我发现了一个快速深入克隆的模块:https://github.com/alexeykupershtokh/node -v8克隆

#16


0  

There is no built-in way to do a real clone (deep copy) of an object in node.js. There are some tricky edge cases so you should definitely use a library for this. I wrote such a function for my simpleoo library. You can use the deepCopy function without using anything else from the library (which is quite small) if you don't need it. This function supports cloning multiple data types, including arrays, dates, and regular expressions, it supports recursive references, and it also works with objects whose constructor functions have required parameters.

在node.js中,没有一个内置的方法可以做一个真正的克隆(deep copy)。有一些棘手的边缘情况,所以你一定要使用一个库。我为simpleoo库编写了这样一个函数。如果不需要的话,您可以使用deepCopy函数,而不使用库中的任何其他东西(它非常小)。这个函数支持克隆多个数据类型,包括数组、日期和正则表达式,它支持递归引用,并且它还可以与具有所需参数的构造函数的对象一起工作。

Here is the code:

这是代码:

//If Object.create isn't already defined, we just do the simple shim, without the second argument,
//since that's all we need here
var object_create = Object.create;
if (typeof object_create !== 'function') {
    object_create = function(o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

/**
 * Deep copy an object (make copies of all its object properties, sub-properties, etc.)
 * An improved version of http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone
 * that doesn't break if the constructor has required parameters
 * 
 * It also borrows some code from http://*.com/a/11621004/560114
 */ 
function deepCopy = function deepCopy(src, /* INTERNAL */ _visited) {
    if(src == null || typeof(src) !== 'object'){
        return src;
    }

    // Initialize the visited objects array if needed
    // This is used to detect cyclic references
    if (_visited == undefined){
        _visited = [];
    }
    // Ensure src has not already been visited
    else {
        var i, len = _visited.length;
        for (i = 0; i < len; i++) {
            // If src was already visited, don't try to copy it, just return the reference
            if (src === _visited[i]) {
                return src;
            }
        }
    }

    // Add this object to the visited array
    _visited.push(src);

    //Honor native/custom clone methods
    if(typeof src.clone == 'function'){
        return src.clone(true);
    }

    //Special cases:
    //Array
    if (Object.prototype.toString.call(src) == '[object Array]') {
        //[].slice(0) would soft clone
        ret = src.slice();
        var i = ret.length;
        while (i--){
            ret[i] = deepCopy(ret[i], _visited);
        }
        return ret;
    }
    //Date
    if (src instanceof Date) {
        return new Date(src.getTime());
    }
    //RegExp
    if (src instanceof RegExp) {
        return new RegExp(src);
    }
    //DOM Element
    if (src.nodeType && typeof src.cloneNode == 'function') {
        return src.cloneNode(true);
    }

    //If we've reached here, we have a regular object, array, or function

    //make sure the returned object has the same prototype as the original
    var proto = (Object.getPrototypeOf ? Object.getPrototypeOf(src): src.__proto__);
    if (!proto) {
        proto = src.constructor.prototype; //this line would probably only be reached by very old browsers 
    }
    var ret = object_create(proto);

    for(var key in src){
        //Note: this does NOT preserve ES5 property attributes like 'writable', 'enumerable', etc.
        //For an example of how this could be modified to do so, see the singleMixin() function
        ret[key] = deepCopy(src[key], _visited);
    }
    return ret;
};

#17


0  

npm install node-v8-clone

Fastest cloner, it open native clone method from node.js

最快的cloner,它打开了来自node.js的本地克隆方法。

var clone = require('node-v8-clone').clone;
var newObj = clone(obj, true); //true - deep recursive clone

#18


-1  

You can prototype object and then call object instance every time you want to use and change object:

你可以原型对象,然后调用对象实例每次你想要使用和改变对象:

function object () {
  this.x = 5;
  this.y = 5;
}
var obj1 = new object();
var obj2 = new object();
obj2.x = 6;
console.log(obj1.x); //logs 5

You can also pass arguments to object constructor

还可以将参数传递给对象构造函数

function object (x, y) {
   this.x = x;
   this.y = y;
}
var obj1 = new object(5, 5);
var obj2 = new object(6, 6);
console.log(obj1.x); //logs 5
console.log(obj2.x); //logs 6

Hope this is helpful.

希望这是有帮助的。

#1


253  

Possibility 1

Low-frills deep copy:

Low-frills深拷贝:

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

Possibility 2 (deprecated)

Attention: This solution is now marked as deprecated in the documentation of Node.js:

注意:这个解决方案现在在Node.js的文档中被标记为不赞成:

The util._extend() method was never intended to be used outside of internal Node.js modules. The community found and used it anyway.

不打算在内部节点外部使用util._extend()方法。js模块。社区找到并使用了它。

It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign().

它已被弃用,不应在新代码中使用。JavaScript通过Object.assign()提供了非常类似的内置功能。

Original answer::

原来的答案::

For a shallow copy, use Node's built-in util._extend() function.

对于浅拷贝,使用Node的内置util._extend()函数。

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

var obj1 = {x: 5, y:5};
var obj2 = extend({}, obj1);
obj2.x = 6;
console.log(obj1.x); // still logs 5

Source code of Node's _extend function is in here: https://github.com/joyent/node/blob/master/lib/util.js

Node的_extend函数的源代码在这里:https://github.com/joyent/node/blob/master/lib/util.js

exports._extend = function(origin, add) {
  // Don't do anything if add isn't an object
  if (!add || typeof add !== 'object') return origin;

  var keys = Object.keys(add);
  var i = keys.length;
  while (i--) {
    origin[keys[i]] = add[keys[i]];
  }
  return origin;
};

#2


165  

I'm surprised Object.assign hasn't been mentioned.

我很惊讶对象。分配还没有提到。

let cloned = Object.assign({}, source);

If available (e.g. Babel), you can use the object spread operator:

如果有的话(例如,Babel),你可以使用对象扩展运算符:

let cloned = { ... source };

#3


23  

Object.defineProperty(Object.prototype, "extend", {
    enumerable: false,
    value: function(from) {
        var props = Object.getOwnPropertyNames(from);
        var dest = this;
        props.forEach(function(name) {
            if (name in dest) {
                var destination = Object.getOwnPropertyDescriptor(from, name);
                Object.defineProperty(dest, name, destination);
            }
        });
        return this;
    }
});

This will define an extend method that you can use. Code comes from this article.

这将定义一个扩展方法,您可以使用它。代码来自本文。

#4


16  

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

#5


13  

You can use the extend function from JQuery:

您可以使用JQuery的扩展函数:

var newClone= jQuery.extend({}, oldObject);  
var deepClone = jQuery.extend(true, {}, oldObject); 

There is a Node.js Plugin too:

有一个节点。js插件:

https://github.com/shimondoodkin/nodejs-clone-extend

https://github.com/shimondoodkin/nodejs-clone-extend

To do it without JQuery or Plugin read this here:

在没有JQuery或插件的情况下,请阅读以下内容:

http://my.opera.com/GreyWyvern/blog/show.dml/1725165

http://my.opera.com/GreyWyvern/blog/show.dml/1725165

#6


12  

Check out underscore.js. It has both clone and extend and many other very useful functions.

查看underscore.js。它具有克隆和扩展以及许多其他非常有用的功能。

This can be useful: Using the Underscore module with Node.js

这可能很有用:使用带有Node.js的下划线模块

#7


8  

There are some Node modules out there if don't want to "roll your own". This one looks good: https://www.npmjs.com/package/clone

如果不想“滚你自己的”,还有一些节点模块。这个看起来不错:https://www.npmjs.com/package/clone

Looks like it handles all kinds of stuff, including circular references. From the github page:

看起来它可以处理各种各样的东西,包括循环引用。从github页面:

clone masters cloning objects, arrays, Date objects, and RegEx objects. Everything is cloned recursively, so that you can clone dates in arrays in objects, for example. [...] Circular references? Yep!

克隆控制克隆对象、数组、日期对象和RegEx对象。所有东西都被递归地克隆,因此您可以在对象的数组中克隆日期。[…循环引用吗?是的!

#8


6  

Simple and the fastest way to clone an Object in NodeJS is to use Object.keys( obj ) method

在node . js中克隆对象的最简单、最快的方法是使用Object。键(obj)方法

var a = {"a": "a11", "b": "avc"};
var b;

for(var keys = Object.keys(a), l = keys.length; l; --l)
{
   b[ keys[l-1] ] = a[ keys[l-1] ];
}
b.a = 0;

console.log("a: " + JSON.stringify(a)); // LOG: a: {"a":"a11","b":"avc"} 
console.log("b: " + JSON.stringify(b)); // LOG: b: {"a":0,"b":"avc"}

The method Object.keys requires JavaScript 1.8.5; nodeJS v0.4.11 supports this method

对象的方法。钥匙需要于JavaScript 1.8.5;nodeJS v0.4.11支持此方法

but of course for nested objects need to implement recursive func

但是,对于嵌套对象,当然需要实现递归函数。


Other solution is to use native JSON (Implemented in JavaScript 1.7), but it's much slower (~10 times slower) than previous one

其他的解决方案是使用本机JSON(在JavaScript 1.7中实现),但是它比以前的要慢很多(大约慢10倍)

var a = {"a": i, "b": i*i};
var b = JSON.parse(JSON.stringify(a));
b.a = 0;

#9


5  

There is also a project on Github that aims to be a more direct port of the jQuery.extend():

Github上还有一个项目,目的是成为jquery.org的一个更直接的端口。

https://github.com/dreamerslab/node.extend

https://github.com/dreamerslab/node.extend

An example, modified from the jQuery docs:

一个例子,修改自jQuery文档:

var extend = require('node.extend');

var object1 = {
    apple: 0,
    banana: {
        weight: 52,
        price: 100
    },
    cherry: 97
};

var object2 = {
    banana: {
        price: 200
    },
    durian: 100
};

var merged = extend(object1, object2);

#10


5  

This code is also work cause The Object.create() method creates a new object with the specified prototype object and properties.

由于object .create()方法使用指定的原型对象和属性创建一个新对象,所以这段代码也可以工作。

var obj1 = {x:5, y:5};

var obj2 = Object.create(obj1);

obj2.x; //5
obj2.x = 6;
obj2.x; //6

obj1.x; //5

#11


4  

There is another library lodash, it has clone and cloneDeep, also many other useful function.

还有一个库lodash,它有克隆和cloneDeep,还有许多其他有用的功能。

#12


3  

Looking for a true clone option, I stumbled across ridcully's link to here:

为了寻找一个真正的克隆选择,我偶然发现了ridcully的链接到这里:

http://my.opera.com/GreyWyvern/blog/show.dml/1725165

http://my.opera.com/GreyWyvern/blog/show.dml/1725165

I modified the solution on that page so that the function attached to the Object prototype is not enumerable. Here is my result:

我在该页上修改了解决方案,以使附加到对象原型的函数不具有可枚举性。这是我的结果:

Object.defineProperty(Object.prototype, 'clone', {
    enumerable: false,
    value: function() {
        var newObj = (this instanceof Array) ? [] : {};
        for (i in this) {
        if (i == 'clone') continue;
            if (this[i] && typeof this[i] == "object") {
                newObj[i] = this[i].clone();
            } else newObj[i] = this[i]
        } return newObj;
    }
});

Hopefully this helps someone else as well. Note that there are some caveats... particularly with properties named "clone". This works well for me. I don't take any credit for writing it. Again, I only changed how it was being defined.

希望这对其他人也有帮助。注意,有一些注意事项……尤其是那些名为“克隆”的属性。这对我很有效。我写这本书没有任何功劳。同样,我只是改变了它的定义。

#13


1  

You can also use SugarJS in NodeJS.

您也可以在NodeJS中使用SugarJS。

http://sugarjs.com/

http://sugarjs.com/

They have a very clean clone feature: http://sugarjs.com/api/Object/clone

他们有一个非常干净的克隆特性:http://sugarjs.com/api/Object/clone。

#14


0  

If you're using coffee-script, it's as easy as:

如果你使用的是咖啡脚本,那么这很简单:

newObject = {}
newObject[key] = value  for own key,value of oldObject

Though this isn't a deep clone.

虽然这不是一个深度克隆。

#15


0  

None of the answers satisfied me, several don't work or are just shallow clones, answers from @clint-harris and using JSON.parse/stringify are good but quite slow. I found a module that does deep cloning fast: https://github.com/AlexeyKupershtokh/node-v8-clone

这些答案中没有一个让我满意,有几个是无效的,或者只是简单的克隆。解析/stringify很好,但是很慢。我发现了一个快速深入克隆的模块:https://github.com/alexeykupershtokh/node -v8克隆

#16


0  

There is no built-in way to do a real clone (deep copy) of an object in node.js. There are some tricky edge cases so you should definitely use a library for this. I wrote such a function for my simpleoo library. You can use the deepCopy function without using anything else from the library (which is quite small) if you don't need it. This function supports cloning multiple data types, including arrays, dates, and regular expressions, it supports recursive references, and it also works with objects whose constructor functions have required parameters.

在node.js中,没有一个内置的方法可以做一个真正的克隆(deep copy)。有一些棘手的边缘情况,所以你一定要使用一个库。我为simpleoo库编写了这样一个函数。如果不需要的话,您可以使用deepCopy函数,而不使用库中的任何其他东西(它非常小)。这个函数支持克隆多个数据类型,包括数组、日期和正则表达式,它支持递归引用,并且它还可以与具有所需参数的构造函数的对象一起工作。

Here is the code:

这是代码:

//If Object.create isn't already defined, we just do the simple shim, without the second argument,
//since that's all we need here
var object_create = Object.create;
if (typeof object_create !== 'function') {
    object_create = function(o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

/**
 * Deep copy an object (make copies of all its object properties, sub-properties, etc.)
 * An improved version of http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone
 * that doesn't break if the constructor has required parameters
 * 
 * It also borrows some code from http://*.com/a/11621004/560114
 */ 
function deepCopy = function deepCopy(src, /* INTERNAL */ _visited) {
    if(src == null || typeof(src) !== 'object'){
        return src;
    }

    // Initialize the visited objects array if needed
    // This is used to detect cyclic references
    if (_visited == undefined){
        _visited = [];
    }
    // Ensure src has not already been visited
    else {
        var i, len = _visited.length;
        for (i = 0; i < len; i++) {
            // If src was already visited, don't try to copy it, just return the reference
            if (src === _visited[i]) {
                return src;
            }
        }
    }

    // Add this object to the visited array
    _visited.push(src);

    //Honor native/custom clone methods
    if(typeof src.clone == 'function'){
        return src.clone(true);
    }

    //Special cases:
    //Array
    if (Object.prototype.toString.call(src) == '[object Array]') {
        //[].slice(0) would soft clone
        ret = src.slice();
        var i = ret.length;
        while (i--){
            ret[i] = deepCopy(ret[i], _visited);
        }
        return ret;
    }
    //Date
    if (src instanceof Date) {
        return new Date(src.getTime());
    }
    //RegExp
    if (src instanceof RegExp) {
        return new RegExp(src);
    }
    //DOM Element
    if (src.nodeType && typeof src.cloneNode == 'function') {
        return src.cloneNode(true);
    }

    //If we've reached here, we have a regular object, array, or function

    //make sure the returned object has the same prototype as the original
    var proto = (Object.getPrototypeOf ? Object.getPrototypeOf(src): src.__proto__);
    if (!proto) {
        proto = src.constructor.prototype; //this line would probably only be reached by very old browsers 
    }
    var ret = object_create(proto);

    for(var key in src){
        //Note: this does NOT preserve ES5 property attributes like 'writable', 'enumerable', etc.
        //For an example of how this could be modified to do so, see the singleMixin() function
        ret[key] = deepCopy(src[key], _visited);
    }
    return ret;
};

#17


0  

npm install node-v8-clone

Fastest cloner, it open native clone method from node.js

最快的cloner,它打开了来自node.js的本地克隆方法。

var clone = require('node-v8-clone').clone;
var newObj = clone(obj, true); //true - deep recursive clone

#18


-1  

You can prototype object and then call object instance every time you want to use and change object:

你可以原型对象,然后调用对象实例每次你想要使用和改变对象:

function object () {
  this.x = 5;
  this.y = 5;
}
var obj1 = new object();
var obj2 = new object();
obj2.x = 6;
console.log(obj1.x); //logs 5

You can also pass arguments to object constructor

还可以将参数传递给对象构造函数

function object (x, y) {
   this.x = x;
   this.y = y;
}
var obj1 = new object(5, 5);
var obj2 = new object(6, 6);
console.log(obj1.x); //logs 5
console.log(obj2.x); //logs 6

Hope this is helpful.

希望这是有帮助的。