克隆一个JavaScript对象? [英] Cloning a JavaScript object?

查看:104
本文介绍了克隆一个JavaScript对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何克隆js对象?

这是另一种方式创建一个javascript对象(使用对象文字符号而不是函数):

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

user = {
  name: "Foo",
  email: "bar@baz.com"
}

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

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

推荐答案

试试这个:

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

这是发生了什么。


  • 克隆是一个虚拟构造函数。

  • 我们将要克隆的对象分配给克隆构造函数的原型。

  • 我们调用使用'new'克隆,因此构造的对象具有原始对象作为其构造函数的原型又名(非标准) __ proto __

  • 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__.

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

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.

在chrome或firebug控制台中尝试:

Try this in chrome or firebug console:

var user = {
  name: "Foo",
  email: "bar@baz.com"
}

var clonedUser = clone(user);

console.dir(clonedUser);






可以找到有关此克隆技术的详细说明此处

这篇关于克隆一个JavaScript对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆