Currently JavaScript provides no native methods to implement the cloning of an object. Cloning an object means having another object whose properties and methods are an exact copy of the original's properties and methods. Although this is considered a bad practice, I'm going to show you how to achieve this by augmenting the prototype
object of the native Object
class. For example, if we have an object literal like this:
var Class = { property1: 'Test', property2: 'Foo', method: function() { alert('Baz'); } };
We can augment the prototype
object of the Object
class this way:
// Check first if this method has already been implemented natively. Object.prototype.clone = function(obj) { if(typeof obj === 'object') { obj = new Object(); for(var i in this) { obj.constructor.prototype[i] = this[i]; } return obj; } else { throw new Error('clone() works only on objects.'); } };
As you can see, we return a copy of the original object with all its methods and properties by dynamically augmenting its prototype
property. Some tests:
var Class2 = {}; Class.clone(Class2); Class2.method(); // alerts 'Baz' alert(Class2.property1); // alerts 'Test'