如何克隆JavaScript类实例? [英] How do I clone a JavaScript class instance?

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

问题描述

如何克隆JavaScript类实例?

How do I clone a JavaScript class instance?

我尝试了普通的jQuery扩展,但这只是返回一个vanilla对象。我在堆栈上查看了许多其他答案,但找不到如何克隆实例。

I tried the normal jQuery extend, but that just returns a vanilla object. I have looked through many other answers on stack, but could not find how to clone an instance.

function Parent(name) {
    this.name = name;
}

Parent.prototype.sayHello = function() {
    console.log('Hello my name is ' + this.name);
}

function Child(name) {
    Parent.call(this, name);
}

Child.prototype = Object.create(Parent.prototype);

var child = new Child('Billy');

var clone = $.extend(true, {}, child);
clone.name = 'Bob';

child.sayHello();
clone.sayHello();

console.log(child instanceof Child);
console.log(clone instanceof Child);

http:// jsfiddle.net/39gjA/

我希望克隆是深度/递归的。 I.E.作为对象的所有属性也被克隆。

I would prefer that the clone was deep/recursive. I.E. all properties that are objects are cloned as well.

推荐答案


如何克隆JavaScript类实例?

How do I clone a JavaScript class instance?

如果在构造函数中大量使用闭包创建实例,则几乎不可能。我们现在可能永远不会设置哪些内部值,以及如何重现这样的设置。因此,最简单的方法是每个班级都提供一个克隆函数
,它知道该怎么做。

It's hardly possible if the instance was created with heavy use of closures in the constructor function. We may never now which internal values were set, and how to reproduce such a setup. Therefore, the easiest way would be if every class offered a clone function which knows what to do.

普通的jQuery扩展只返回一个vanilla对象

normal jQuery extend just returns a vanilla object

不一定,它返回你传入的内容。使用

Not necessarily, it returns what you passed in. Use

var clone = $.extend(true, Object.create(Object.getPrototypeOf(child)), child);

而你的 instanceof 用法会正常工作。请注意, true 表示深层副本,可能是您想要的,也可能不是。此外, $ .extend 也会愉快地复制可枚举的继承属性,因此您可能需要使用更复杂的 extend 函数。

instead and your instanceof usage will work fine. Note that the true signifies a "deep" copy which may or may not be what you want. Also, $.extend will happily copy enumerable inherited properties as well, so you might need to use a more sophisticated extend function.

或者根本没有jQuery,只复制自己的,可枚举的属性,只使用浅拷贝:

Or without jQuery at all, and only copying own, enumerable properties and only using a shallow copy:

var clone = Object.assign(Object.create(Object.getPrototypeOf(child)), child);

但同样,并非所有对象都会以这种方式克隆,请参阅上面的第一点。

But again, not all objects will be clonable in this way, see my first point above.

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

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