如何克隆 JavaScript 类实例?
我尝试了普通的 jQuery 扩展,但这只是返回一个香草对象。我查看了堆栈上的许多其他答案,但找不到如何克隆实例。
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);
我希望克隆是深度/递归的。IE 所有作为对象的属性也会被克隆。