美文网首页
无标题文章

无标题文章

作者: d0c10592d6af | 来源:发表于2016-09-19 21:54 被阅读0次

Skip to main content

Select language

Skip to search

mozilla

Mozilla Developer Network

Sign in

WEB PLATFORM

MOZILLA DOCS

DEVELOPER TOOLS

FEEDBACK

SearchSEARCH

LANGUAGES

EDIT

ADVANCED

MDN

Web technology For developers

JavaScript

JavaScript reference

Standard built-in objects

Object

Object.assign()

see all contributors

Object.assign()

IN THIS ARTICLE

Syntax

Parameters

Return value

Description

Examples

Cloning an object

Warning for Deep Clone

Merging objects

Merging objects with same properties

Copying symbol-typed properties

Properties on the prototype chain and non-enumerable properties cannot be copied

Primitives will be wrapped to objects

Exceptions will interrupt the ongoing copying task

Copying accessors

Polyfill

Specifications

Browser compatibility

See also

TheObject.assign()method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Syntax

Object.assign(target, ...sources)

Parameters

target

The target object.

sources

The source object(s).

Return value

The target object.

Description

Properties in the target object will be overwritten by properties in the sources if they have the same key.  Later sources' properties will similarly overwrite earlier ones.

TheObject.assign()method only copiesenumerableandownproperties from a source object to a target object. It uses[[Get]]on the source and[[Set]]on the target, so it will invoke getters and setters. Therefore itassignsproperties versus just copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters. For copying property definitions, including their enumerability, into prototypesObject.getOwnPropertyDescriptor()andObject.defineProperty()should be used instead.

BothStringandSymbolproperties are copied.

In case of an error, for example if a property is non-writable, aTypeErrorwill be raised, and thetargetobject remains unchanged.

Note thatObject.assign()does not throw onnullorundefinedsource values.

Examples

Cloning an object

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

Warning for Deep Clone

For deep cloning, we need to use other alternatives. This is becauseObject.assign()copies the property reference when the property being assigned is an object.

functiontest(){leta={b:{c:4},d:{e:{f:1}}}letg=Object.assign({},a)leth=JSON.parse(JSON.stringify(a));console.log(g.d)// { e: { f: 1 } }g.d.e=32console.log('g.d.e set to 32.')// g.d.e set to 32.console.log(g)// { b: { c: 4 }, d: { e: 32 } }console.log(a)// { b: { c: 4 }, d: { e: 32 } }console.log(h)// { b: { c: 4 }, d: { e: { f: 1 } } }h.d.e=54console.log('h.d.e set to 54.')// h.d.e set to 54.console.log(g)// { b: { c: 4 }, d: { e: 32 } }console.log(a)// { b: { c: 4 }, d: { e: 32 } }console.log(h)// { b: { c: 4 }, d: { e: 54 } }}test();

Merging objects

varo1={a:1};varo2={b:2};varo3={c:3};varobj=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.

Merging objects with same properties

varo1={a:1,b:1,c:1};varo2={b:2,c:2};varo3={c:3};varobj=Object.assign({},o1,o2,o3);console.log(obj);// { a: 1, b: 2, c: 3 }

The properties are overwritten by other objects that have the same properties later in the parameters order.

Copying symbol-typed properties

varo1={a:1};varo2={[Symbol('foo')]:2};varobj=Object.assign({},o1,o2);console.log(obj);// { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox)Object.getOwnPropertySymbols(obj);// [Symbol(foo)]

Properties on the prototype chain and non-enumerable properties cannot be copied

varobj=Object.create({foo:1},{// foo is on obj's prototype chain.bar:{value:2// bar is a non-enumerable property.},baz:{value:3,enumerable:true// baz is an own enumerable property.}});varcopy=Object.assign({},obj);console.log(copy);// { baz: 3 }

Primitives will be wrapped to objects

varv1='abc';varv2=true;varv3=10;varv4=Symbol('foo');varobj=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": "a", "1": "b", "2": "c" }

Exceptions will interrupt the ongoing copying task

vartarget=Object.defineProperty({},'foo',{value:1,writable: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.

Copying accessors

varobj={foo:1,getbar(){return2;}};varcopy=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 that copies full descriptorsfunctioncompleteAssign(target,...sources){sources.forEach(source=>{letdescriptors=Object.keys(source).reduce((descriptors,key)=>{descriptors[key]=Object.getOwnPropertyDescriptor(source,key);returndescriptors;},{});// by default, Object.assign copies enumerable Symbols tooObject.getOwnPropertySymbols(source).forEach(sym=>{letdescriptor=Object.getOwnPropertyDescriptor(source,sym);if(descriptor.enumerable){descriptors[sym]=descriptor;}});Object.defineProperties(target,descriptors);});returntarget;}varcopy=completeAssign({},obj);console.log(copy);// { foo:1, get bar() { return 2 } }

Polyfill

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

if(typeofObject.assign!='function'){(function(){Object.assign=function(target){'use strict';// We must check against these specific cases.if(target===undefined||target===null){thrownewTypeError('Cannot convert undefined or null to object');}varoutput=Object(target);for(varindex=1;index

Specifications

SpecificationStatusComment

ECMAScript 2015 (6th Edition, ECMA-262)

The definition of 'Object.assign' in that specification.StandardInitial definition.

ECMAScript 2017 Draft (ECMA-262)

The definition of 'Object.assign' in that specification.Draft

Browser compatibility

Desktop

Mobile

FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari

Basic support4534(34)No support(Yes)329

See also

Object.defineProperties()

Enumerability and ownership of properties

Document Tags and Contributors

Tags:

ECMAScript6

JavaScript

Method

Object

polyfill

Reference

Contributors to this page:sjohnsonaz,RocAlayo,Asuza,Ende93,HarrisonB,SphinxKnight,Normanlife,allan-bonadio,eduardoboucas,chharvey,popigg,bergus,fscholz,taiyaki32p,irnc,ajmichaels,jacksonrayhamilton,iamchenxin,Willson,WebReflection,jiraiya,rwaldron,pixelkritzel,SamuelMarks,marxus,makowski,yan,vaibhavsinghal87,andrewashbacher,nicolo-ribaudo,roczinskisquared,Mingun,olegskl,ziyunfei,kdex,The_8472,davezatch,Waldo,evilpie,megawac,dbruant

Last updated by:sjohnsonaz,Sep 14, 2016, 10:35:52 AM

SEE ALSO

Standard built-in objects

Object

Properties

Object.prototype

Object.prototype.__count__

Object.prototype.__noSuchMethod__

Object.prototype.__parent__

Object.prototype.__proto__

Object.prototype.constructor

Methods

Object.assign()

Object.create()

Object.defineProperties()

Object.defineProperty()

Object.entries()

Object.freeze()

Object.getNotifier()

Object.getOwnPropertyDescriptor()

Object.getOwnPropertyDescriptors()

Object.getOwnPropertyNames()

Object.getOwnPropertySymbols()

Object.getPrototypeOf()

Object.is()

Object.isExtensible()

Object.isFrozen()

Object.isSealed()

Object.keys()

Object.observe()

Object.preventExtensions()

Object.prototype.__defineGetter__()

Object.prototype.__defineSetter__()

Object.prototype.__lookupGetter__()

Object.prototype.__lookupSetter__()

Object.prototype.eval()

Object.prototype.hasOwnProperty()

Object.prototype.isPrototypeOf()

Object.prototype.propertyIsEnumerable()

Object.prototype.toLocaleString()

Object.prototype.toSource()

Object.prototype.toString()

Object.prototype.unwatch()

Object.prototype.valueOf()

Object.prototype.watch()

Object.seal()

Object.setPrototypeOf()

Object.unobserve()

Object.values()

Inheritance:

Function

Properties

Methods

© 2005-2016 Mozilla Developer Network and individual contributors.

Content is available underthese licenses.

About MDN

Terms

Privacy

Cookies

Contribute to the code

Other languages:English (US) (en-US)Català (ca)Deutsch (de)Español (es)Français (fr)Italiano (it)日本語 (ja)Português (do Brasil) (pt-BR)Русский (ru)中文 (简体) (zh-CN)

相关文章

  • 无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标

    无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章 无标题文章无标题文章无标题文章无...

  • 无标题文章

    无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章

  • 无标题文章

    无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标...

  • 无标题文章

    无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标...

  • fasfsdfdf

    无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标...

  • 无标题文章

    无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标...

  • 无标题文章

    无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标...

  • 无标题文章

    无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标...

  • 无标题文章

    无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章无标题文章

  • 无标题文章

    无标题文章 无标题文章 无标题文章无标题文章 无标题文章 无标题文章

网友评论

      本文标题:无标题文章

      本文链接:https://www.haomeiwen.com/subject/oyvnettx.html