--- title: Object.assign() slug: Web/JavaScript/Reference/Global_Objects/Object/assign translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign ---
{{JSRef}}

El mètode Object.assign() s'utilitza per copiar els valors de totes les propietats enumerables pròpies d'un o més objectes d'orígens a un objecte objectiu o destí. Retornarà l'objecte destí.

Sintaxi

Object.assign(target, ...orígens)

Paràmetres

target
L'objecte destí.
sources
El(s) objecte(s) d'orígen.

Valor retornat

L'objecte destí (o objectiu) es retornat.

Descripció

El mètode Object.assign() només copia propietats enumerables i pròpies d'un objecte orígen a un objecte destí. S'utilitza [[Get]] a l'orígen i [[Put]] al destí, de forma que invocarà getters i setters. Per tant, assigna propietats en comptes de només copiar o definir noves propietats. Axò pot fer que sigui inadequat per juntar noves propietats en un prototipus si les fonts de la unió contenen getters. Per copiar definicions de la propietat, incloent la seva enumerabilitat, en prototipus s'ha de fer servir {{jsxref("Object.getOwnPropertyDescriptor()")}} i {{jsxref("Object.defineProperty()")}}.

Tant la propietat {{jsxref("String")}} com la propietat {{jsxref("Symbol")}} són copiades.

En cas d'error, per exemple si una propietat no és modificable, un {{jsxref("TypeError")}} s'incrementarà i l'objecte target object es mantindrà sense canvis.

Vegeu que Object.assign() does not throw on {{jsxref("null")}} or {{jsxref("undefined")}} source values.

Exemples

Clonar un objecte

var obj = { a: 1 };
var copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }

Unir objectes

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1);  // { a: 1, b: 2, c: 3 }, L'objecte de destinació es canvia

Copiar propietats  symbol-typed

var o1 = { a: 1 };
var o2 = { [Symbol('foo')]: 2 };

var obj = Object.assign({}, o1, o2);
console.log(obj); // { a: 1, [Symbol("foo")]: 2 }

Les propietats heretades i les propietats no enumerables no es poden copiar

var obj = Object.create({ foo: 1 }, { // foo és una propietat heretada.
  bar: {
    value: 2  // bar és una propietat no enumerable.
  },
  baz: {
    value: 3,
    enumerable: true  // baz is an own enumerable property.
  }
});

var copy = Object.assign({}, obj);
console.log(copy); // { baz: 3 }

Primitives will be wrapped to objects

var v1 = '123';
var v2 = true;
var v3 = 10;
var v4 = Symbol('foo')

var obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
// Primitives will be wrapped, null and undefined will be ignored.
// Note, only string wrappers can have own enumerable properties.
console.log(obj); // { "0": "1", "1": "2", "2": "3" }

Exceptions will interrupt the ongoing copying task

var target = Object.defineProperty({}, 'foo', {
  value: 1,
  writeable: false
}); // target.foo is a read-only property

Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
// TypeError: "foo" is read-only
// The Exception is thrown when assigning target.foo

console.log(target.bar);  // 2, the first source was copied successfully.
console.log(target.foo2); // 3, the first property of the second source was copied successfully.
console.log(target.foo);  // 1, exception is thrown here.
console.log(target.foo3); // undefined, assign method has finished, foo3 will not be copied.
console.log(target.baz);  // undefined, the third source will not be copied either.

Copying accessors

var obj = {
  foo: 1,
  get bar() {
    return 2;
  }
};

var copy = Object.assign({}, obj);
console.log(copy);
// { foo: 1, bar: 2 }, the value of copy.bar is obj.bar's getter's return value.

// This is an assign function which can copy accessors.
function myAssign(target, ...sources) {
  sources.forEach(source => {
    Object.defineProperties(target, Object.keys(source).reduce((descriptors, key) => {
      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
      return descriptors;
    }, {}));
  });
  return target;
}

var copy = myAssign({}, obj);
console.log(copy);
// { foo:1, get bar() { return 2 } }

Polyfill

This polyfill doesn't support symbol properties, since ES5 doesn't have symbols anyway:

if (!Object.assign) {
  Object.defineProperty(Object, 'assign', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function(target) {
      'use strict';
      if (target === undefined || target === null) {
        throw new TypeError('Cannot convert first argument to object');
      }

      var to = Object(target);
      for (var i = 1; i < arguments.length; i++) {
        var nextSource = arguments[i];
        if (nextSource === undefined || nextSource === null) {
          continue;
        }
        nextSource = Object(nextSource);

        var keysArray = Object.keys(Object(nextSource));
        for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
          var nextKey = keysArray[nextIndex];
          var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
          if (desc !== undefined && desc.enumerable) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
      return to;
    }
  });
}

Especificacions

Especificació Estat Comentaris
{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}} {{Spec2('ES2015')}} Definició inicial

Compatibilitat de navegadors

{{CompatibilityTable}}
Caracteristica Chrome Firefox (Gecko) Internet Explorer Opera Safari
Suport bàsic {{CompatChrome("45")}} {{CompatGeckoDesktop("34")}} {{CompatNo}} {{CompatNo}} {{CompatNo}}
Característica Android Chrome per Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Suport bàsic {{CompatNo}} {{CompatNo}} {{CompatGeckoMobile("34")}} {{CompatNo}} {{CompatNo}} {{CompatNo}}

Vegeu també