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 sta
I think that not necessarily needs to work with classes(or functions instances), you could extend prototype to apply OOP. My suggestion is that you extend prototype instead of create classes. jQuery is for DOM but not for advance object treatment so while $.extend could be helpful in some cases for complex stuff there are more advanced libraries.
You could use libraries like CloneJS to easily work with extendable objects: https://npmjs.org/package/clonejs
Just include this script: http://quadroid.github.io/clonejs/cdn/clone.min.js
And try their own example:
/// Forget about classes.
// Instead of creating class (function), create prototype (object):
var $duck = $object.clone({
name: 'Unnamed',
quack: function(){
console.log( this.name +' Duck: Quack-quack!');
}
});
$duck.quack();//Unnamed Duck: Quack-quack!
/// Inheritance is simple:
var $talkingDuck = $duck.clone({
quack: function(){
this.applySuper('quack');
console.log('My name is '+ this.name +'!');
}
});
/// Forget about the `new` operator, use .create() method instead:
var donald = $talkingDuck.create({name: 'Donald'});
donald.quack();// Donald Duck: Quack-quack! My name is Donald!
/// Forget about the `instanceof` operator, use JS native
// .isPrototypeOf() method instead:
$duck.isPrototypeOf(donald);// true
Also I think that Backbone.js applies the extension of prototype instead of creation of classes. They use _.extend
Some more references: http://www.2ality.com/2011/11/javascript-classes.html http://underscorejs.org/#extend