diff options
Diffstat (limited to 'files/pt-br/web/javascript/reference/global_objects/object/assign/index.html')
| -rw-r--r-- | files/pt-br/web/javascript/reference/global_objects/object/assign/index.html | 223 |
1 files changed, 223 insertions, 0 deletions
diff --git a/files/pt-br/web/javascript/reference/global_objects/object/assign/index.html b/files/pt-br/web/javascript/reference/global_objects/object/assign/index.html new file mode 100644 index 0000000000..87d62130d2 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/object/assign/index.html @@ -0,0 +1,223 @@ +--- +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 => { + 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 } } +</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 < 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; + } + }); +} +</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="Compatibilidade_nos_navegadores">Compatibilidade nos navegadores</h2> + +<div class="hidden"> +<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> +</div> + +<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> |
