Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

jquery - How do I clone a JavaScript class instance?

How do I clone a JavaScript class instance?

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 would prefer that the clone was deep/recursive. I.E. all properties that are objects are cloned as well.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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);

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...