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;
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…