Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

javascript - 在Node.js中克隆对象(Cloning an Object in Node.js)

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

(在node.js中克隆对象的最佳方法是什么)

eg 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.

(该对象很可能包含复杂的类型作为属性,因此简单的for(var1 in obj1)无法解决。)

Do I need to write a recursive clone myself or is there something built in that I'm not seeing?

(我需要自己编写一个递归克隆,还是内置一些我看不到的东西?)

  ask by slifty translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Possibility 1(可能性1)

Low-frills deep copy:

(简洁的深层副本:)

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

Possibility 2 (deprecated)(可能性2(已弃用))

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.

(从未打算在内部Node.js模块之外使用util._extend()方法。)

The community found and used it anyway.

(社区仍然找到并使用了它。)

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;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...