Search code examples
javascriptecmascript-5

Assign to object passed as argument in ES5


I have an object that I pass as an argument into a function. Inside that function I want to assign to it a different value, but because inside the function we have only reference to the original object we can not use simple assignment with =.

In ES2015 I could use Object.assign

Is there a workaround I could use in ES5, other than copying properties to the reference?

Here is an example https://jsbin.com/wimuvaqosi/1/edit?js,console

var x = {prop:1};

function foo(x1) {
  var y = {prop:2};
  x1 = y; //this obviously does not work
  //x1 = Object.assign(x1, y); //this works only in ES2015
}

foo(x);

console.log("x ", x);

Solution

  • Is there a workaround I could use in ES5, other than copying properties to the reference?

    Not really, Object.assign also just copies properties. But you can simply use the polyfill and use Object.assign() in your pre es2015 code:

    if (typeof Object.assign != 'function') {
      Object.assign = function(target) {
        'use strict';
        if (target == null) {
          throw new TypeError('Cannot convert undefined or null to object');
        }
    
        target = Object(target);
        for (var index = 1; index < arguments.length; index++) {
          var source = arguments[index];
          if (source != null) {
            for (var key in source) {
              if (Object.prototype.hasOwnProperty.call(source, key)) {
                target[key] = source[key];
              }
            }
          }
        }
        return target;
      };
    }