Movatterモバイル変換


[0]ホーム

URL:


  1. Tecnologia Web para desenvolvedores
  2. JavaScript
  3. Referência JavaScript
  4. Objetos Globais
  5. Object
  6. Object.assign()

Esta página foi traduzida do inglês pela comunidade.Saiba mais e junte-se à comunidade MDN Web Docs.

View in EnglishAlways switch to English

Object.assign()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨setembro de 2015⁩.

O métodoObject.assign() é usado para copiar os valores de todas as propriedades próprias enumeráveis de um ou mais objetosde origem para um objetodestino. Este método irá retornar o objetodestino.

Experimente

const target = { a: 1, b: 2 };const source = { b: 4, c: 5 };const returnedTarget = Object.assign(target, source);console.log(target);// Expected output: Object { a: 1, b: 4, c: 5 }console.log(returnedTarget === target);// Expected output: true

Sintaxe

Object.assign(destino, ...origens)

Parâmetros

destino

O objetodestino.

origens

Um ou mais objetos deorigem.

Valor retornado

O objetodestino será retornado.

Descrição

O métodoObject.assign() copia apenas propriedadesenumeráveis epróprias de um objetode origem para um objeto destino. Ele usa[[Get]] na origem e[[Put]] nodestino, então isto irá invocargetters esetters.

Portanto, eleatribui propriedades, em vez de simplesmente copiar ou definir novas propriedades. Isso pode fazê-lo impróprio para combinar novas propriedades com umprototype se os objetosde origem contiverem getters. Para copiar definições de propriedades, incluindo sua enumerabilidade, paraprototypesObject.getOwnPropertyDescriptor() eObject.defineProperty() devem ser utilizadas no lugar.

Ambas as propriedadesString eSymbol são copiadas.

No caso de erro, por exemplo, se uma propriedade não éwritable, umTypeError será lançado e o objetodestino permanecerá inalterado. Note queObject.assign() não lança erros caso algum argumentosource sejanull ouundefined.

Exemplos

Clonando um objeto

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

Mesclando objetos

js
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 }, target object itself is changed.

Copiando propriedades Symbol

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

Propriedades herdadas e não enumeráveis não podem ser copiadas

js
var obj = Object.create(  { foo: 1 },  {    // foo is an inherit property.    bar: {      value: 2, // bar is a non-enumerable property.    },    baz: {      value: 3,      enumerable: true, // baz is an own enumerable property.    },  },);var copy = Object.assign({}, obj);console.log(copy); // { baz: 3 }

Primitivas serão encapsuladas em objetos

js
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" }

Exceções irão interromper a tarefa de cópia em execução

js
var target = Object.defineProperty({}, "foo", {  value: 1,  writeable: false,}); // target.foo is a read-only propertyObject.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });// TypeError: "foo" is read-only// The Exception is thrown when assigning target.fooconsole.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.

Copiando acessores

js
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

Este polyfill não suporta propriedadesSymbol, visto que ES5 não possui símbolos:

js
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;    },  });}

Especificações

Specification
ECMAScript® 2026 Language Specification
# sec-object.assign

Compatibilidade com navegadores

Veja também

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp