javascript interactive

JavaScript Interactive — a console crash course


5.4 Clones & Mix-Ins

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
>>>
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.
>>>
clone({ a: 1, b: 2 })
{ a: 1, b: 2 }
The cloned object is similar to the original in almost any way, even reflecting future changes. In modern environments, this is available as the Object.create() function.
>>>
print(clone({ a: 1, b: 2 }), true);

  
A debug printout shows the prototype chain in detail.
>>>
clone('test')
{}
There are limits to clone(), however. Most of the built-in objects (Array, String, etc) do no use normal properties to store internal state, so results may be unexpected.
>>>
function mixin(dst, src) {
    dst = dst || {};
    for (var k in src) {
        dst[k] = src[k];
    }
    return dst;
}

  
Another common pattern is to mix properties from two objects. In this example, the mixin() function adds all properties from the second object to 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(null, { a: 1, b: 2 })
{ "a": 1, "b": 2 }
When the first argument is null, the function will return a copy of the second object. Differing from clone(), this copy is not linked to the source object.
>>>

Index 1 2 3 4 5 6 7 8