Skip to content

Instantly share code, notes, and snippets.

@jpalala
Created June 7, 2022 03:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpalala/12b80ed57a88fbf3bfe26e80f54d7fe3 to your computer and use it in GitHub Desktop.
Save jpalala/12b80ed57a88fbf3bfe26e80f54d7fe3 to your computer and use it in GitHub Desktop.
better object cloning in javascript

A more complete solution relies on ECMAScript 5 and uses definition instead of assignment:

  function update(target) {
        var sources = [].slice.call(arguments, 1);
        sources.forEach(function (source) {
            Object.getOwnPropertyNames(source).forEach(function(propName) {
                Object.defineProperty(target, propName,
                    Object.getOwnPropertyDescriptor(source, propName));
            });
        });
        return target;
    };

We have also used ECMAScript 5 functions instead of Underscore functions. The above function is therefore completely independent of that library. update gives you a simple way to clone an object:

function clone(obj) {
        var copy = Object.create(Object.getPrototypeOf(obj));
        update(copy, obj);
        return copy;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment