克隆一个 JavaScript 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3774008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:05:42  来源:igfitidea点击:

Cloning a JavaScript object?

javascript

提问by never_had_a_name

Possible Duplicate:
How to clone js object?

可能的重复:
如何克隆 js 对象?

This is another way to create a javascript object (using object literal notation instead of function):

这是创建 javascript 对象的另一种方法(使用对象文字表示法而不是函数):

user = {
  name: "Foo",
  email: "[email protected]"
}

Is there a way to clone this object or is it a singleton?

有没有办法克隆这个对象或者它是一个单例?

回答by Dagg Nabbit

Try this:

尝试这个:

var clone = (function(){ 
  return function (obj) { Clone.prototype=obj; return new Clone() };
  function Clone(){}
}());

Here's what's going on.

这是发生了什么。

  • Clone is a dummy constructor.
  • We assign the object we want to clone to the Clone constructor's prototype.
  • We call Clone using 'new', so the constructed object has the original object as its constructor's prototype aka (non-standard) __proto__.
  • Clone 是一个虚拟构造函数。
  • 我们将要克隆的对象分配给 Clone 构造函数的原型。
  • 我们使用 'new' 调用 Clone,因此构造的对象将原始对象作为其构造函数的原型,又名(非标准)__proto__

The cloned object will share all the properties of the original object without any copies of anything being made. If properties of the cloned object are assigned new values, they won't interfere with the original object. And no tampering of built-ins is required.

克隆的对象将共享原始对象的所有属性,而不会制作任何副本。如果为克隆对象的属性分配了新值,它们将不会干扰原始对象。并且不需要篡改内置插件。

Keep in mind that an object property of the newly-created object will refer to the same object as the eponymous property of the cloned object. Assigning a new value to a property of the clone won't interfere with the original, but assigning values to the clone's object properties will.

请记住,新创建对象的对象属性将引用与克隆对象的同名属性相同的对象。为克隆的属性分配新值不会干扰原始值,但为克隆的对象属性分配值会干扰。



Try this in chrome or firebug console:

在 chrome 或 firebug 控制台中试试这个:

var user = {
  name: "Foo",
  email: "[email protected]"
}

var clonedUser = clone(user);

console.dir(clonedUser);


A detailed explanation of this cloning technique can be found here.

可以在此处找到对这种克隆技术的详细说明。

回答by Topera

You can use JSON object (present in modern browsers):

您可以使用 JSON 对象(存在于现代浏览器中):

var user = {name: "Foo", email: "[email protected]" } 
var user2 = JSON.parse(JSON.stringify(user))

user2.name = "Bar";
alert(user.name + " " + user2.name); // Foo Bar

See in jsfiddle.

请参阅jsfiddle



EDIT

编辑

If you need this in older browsers, see http://www.json.org/js.html.

如果您在旧浏览器中需要此功能,请参阅http://www.json.org/js.html

回答by Chris J

I like to use this:

我喜欢用这个:

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        var F = function () {};
        F.prototype = o;
    return new F();
    };
}

then any object I want to clone can be done as:

那么我想克隆的任何对象都可以这样做:

user = {
    name: "Foo",
    email: "[email protected]"
};
var user2 = Object.create(user);

As shown in (or similar to) JavaScript The Good Parts

如(或类似)JavaScript The Good Parts 中所示

回答by Jonathan Vanasco

Most of the javascript frameworks have good support for object cloning.

大多数 javascript 框架都对对象克隆有很好的支持。

var a= {'key':'value'};
var b= jQuery.extend( true, {}, a );

回答by vol7ron

Object.prototype.clone = function clone(obj) {
                           obj = obj || this;
                           var new_obj  = {};

                           for( var p in obj ) {
                             if ( obj.hasOwnProperty(p) ) {
                               if( obj[p] !== null && typeof(obj[p]) === "object" ) {
                                 new_obj[p] = clone( obj[p] );
                               }
                               else {
                                 new_obj[p] = obj[p];
                               }
                             }
                           }

                           return new_obj;
                         };


/* Example */
var foo = {
     name:  "Foo"
   , email: "[email protected]"
   , obj:   {a:"A",b:"B"}
};

var bar   = foo.clone();
bar.name  = "Bar";
bar.obj.b = "C";


// foo and bar should have a different 'name'
// foo and bar should retain the same email
// foo and bar should have different values for <foo/bar>['obj']['b']
// foo and bar should have the same values for <foo/bar>['obj']['a']
console.dir(foo);
console.dir(bar);