Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Object.assign()

This translation is incomplete. Please help translate this article from English.

This is a new technology, part of the ECMAScript 2015 (ES6) standard.
This technology's specification has been finalized, but check the compatibility table for usage and implementation status in various browsers.

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 Object.getOwnPropertyDescriptor() i Object.defineProperty().

Tant la propietat String com la propietat Symbol són copiades.

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

Vegeu que Object.assign() does not throw on null or 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
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Object.assign' in that specification.
Standard Definició inicial

Compatibilitat de navegadors

Caracteristica Chrome Firefox (Gecko) Internet Explorer Opera Safari
Suport bàsic 45 34 (34) No support No support No support
Característica Android Chrome per Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Suport bàsic No support No support 34.0 (34) No support No support No support

Vegeu també

Document Tags and Contributors

 Contributors to this page: mariodev12, llue
 Last updated by: mariodev12,