aboutsummaryrefslogtreecommitdiff
path: root/files/pt-br/web/javascript/reference/global_objects/object/assign/index.html
blob: 04e7f1f969fee59647de7a25b0214c65ea9dc9dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
---
title: Object.assign()
slug: Web/JavaScript/Reference/Global_Objects/Object/assign
tags:
  - ECMAScript 2015
  - JavaScript
  - Method
  - Object
  - Reference
  - polyfill
translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign
---
<div>{{JSRef}}</div>

<p>O método <strong><code>Object.assign()</code></strong> é usado para copiar os valores de todas as propriedades próprias enumeráveis de um ou mais objetos <em>de origem</em> para um objeto <em>destino</em>. Este método irá retornar o objeto <em>destino</em>.</p>

<p>{{EmbedInteractiveExample("pages/js/object-assign.html")}}</p>

<div class="hidden">
<p>The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples and</a> send us a pull request.</p>
</div>

<h2 id="Sintaxe">Sintaxe</h2>

<pre class="syntaxbox"><code>Object.assign(<var>destino</var>, ...<em>origens</em>)</code></pre>

<h3 id="Parâmetros">Parâmetros</h3>

<dl>
 <dt><code>destino</code></dt>
 <dd>O objeto <em>destino</em>.</dd>
 <dt><code>origens</code></dt>
 <dd>Um ou mais objetos de <em>origem</em>.</dd>
</dl>

<h3 id="Valor_retornado">Valor retornado</h3>

<p>O objeto <em>destino</em> será retornado.</p>

<h2 id="Descrição">Descrição</h2>

<p>O método <code>Object.assign()</code> copia apenas propriedades <em>enumeráveis</em><em> </em>e<em> próprias</em> de um objeto <em>de origem</em> para um objeto destino. Ele usa <code>[[Get]]</code> na origem e <code>[[Put]]</code> no <em>destino</em>, então isto irá invocar <em>getters</em> e <em>setters</em>.</p>

<p>Portanto, ele <em>atribui</em> propriedades, em vez de simplesmente copiar ou definir novas propriedades. Isso pode fazê-lo impróprio para combinar novas propriedades com um <em>prototype</em> se os objetos <em>de origem</em> contiverem getters. Para copiar definições de propriedades, incluindo sua enumerabilidade, para <em>prototypes</em> {{jsxref("Object.getOwnPropertyDescriptor()")}} e {{jsxref("Object.defineProperty()")}} devem ser utilizadas no lugar.</p>

<p>Ambas as propriedades {{jsxref("String")}} e {{jsxref("Symbol")}} são copiadas.</p>

<p>No caso de erro, por exemplo, se uma propriedade não é <em>writable</em>, um {{jsxref("TypeError")}} será lançado e o objeto <em>destino</em> permanecerá inalterado. Note que <code>Object.assign()</code> não lança erros caso algum argumento <em>source</em> seja {{jsxref("null")}} ou {{jsxref("undefined")}}.</p>

<h2 id="Exemplos">Exemplos</h2>

<h3 id="Clonando_um_objeto">Clonando um objeto</h3>

<pre class="brush: js">var obj = { a: 1 };
var copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
</pre>

<h3 id="Mesclando_objetos">Mesclando objetos</h3>

<pre class="brush: 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.
</pre>

<h3 id="Copiando_propriedades_Symbol">Copiando propriedades Symbol</h3>

<pre class="brush: js">var o1 = { a: 1 };
var o2 = { [Symbol('foo')]: 2 };

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

<h3 id="Propriedades_herdadas_e_não_enumeráveis_não_podem_ser_copiadas">Propriedades herdadas e não enumeráveis não podem ser copiadas</h3>

<pre class="brush: 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 }
</pre>

<h3 id="Primitivas_serão_encapsuladas_em_objetos">Primitivas serão encapsuladas em objetos</h3>

<pre class="brush: 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" }
</pre>

<h3 id="Exceções_irão_interromper_a_tarefa_de_cópia_em_execução">Exceções irão interromper a tarefa de cópia em execução</h3>

<pre class="brush: js">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.
</pre>

<h3 id="Copiando_acessores">Copiando acessores</h3>

<pre class="brush: 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 =&gt; {
    Object.defineProperties(target, Object.keys(source).reduce((descriptors, key) =&gt; {
      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
      return descriptors;
    }, {}));
  });
  return target;
}

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

<h2 id="Polyfill">Polyfill</h2>

<p>Este polyfill não suporta propriedades {{jsxref("Symbol")}}, visto que ES5 não possui símbolos:</p>

<pre class="brush: 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 &lt; 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 &lt; len; nextIndex++) {
          var nextKey = keysArray[nextIndex];
          var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
          if (desc !== undefined &amp;&amp; desc.enumerable) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
      return to;
    }
  });
}
</pre>

<h2 id="Especificações">Especificações</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}</td>
   <td>{{Spec2('ES2015')}}</td>
   <td>Definição inicial</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Compatibilidade com navegadores</h2>

<p>{{Compat("javascript.builtins.Object.assign")}}</p>

<h2 id="Veja_também">Veja também</h2>

<ul>
 <li>{{jsxref("Object.defineProperties()")}}</li>
 <li><a href="/pt-BR/docs/Web/JavaScript/Enumerabilidade_e_posse_de_propriedades">Enumerabilidade e posse de propriedades</a></li>
</ul>