Console Learner — An interactive JavaScript course.


5.2 Clones & Copies

>>>
function clone(o) {
    function F() {};
    F.prototype = o;
    return new F();
}

  
One of the most efficient ways to copy an object is to use it as the prototype for a new object. The clone() function creates a dummy constructor function, sets up the prototype chain, and creates a new (cloned) instance.
>>>
print(clone({ a: 1, b: 2 }), true);

  
The cloned object is similar to the original in almost any way, even reflecting future changes. The built-in Object.create() function provides this functionality and more (since ES5 in 2009).
>>>
clone('test')
{}
There are limits to clone(), however. Most of the built-in objects (Array, RegExp, etc) do not store internal state in properties, so results may be unexpected.
>>>
function mixin(dst, src) {
    for (var k in src) {
        dst[k] = src[k];
    }
    return dst;
}

  
Another common pattern is to merge two objects. In this example, the mixin() function adds all properties from the second object into the first.
>>>
mixin({ a: 1 }, { b: 2, c: 3 })
{ "a": 1, "b": 2, "c": 3 }
The mixin() function makes it easy to merge two objects into one.
>>>
mixin({}, { a: 1, b: 2 })
{ "a": 1, "b": 2 }
If the first argument is {}, a shallow copy is created. Differing from clone(), this copy is not linked to the source object (except for sharing the same value objects). The built-in Object.assign() function works like this (since ES6 in 2015).
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.