无标题文章

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)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,000评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,745评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,561评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,782评论 1 298
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,798评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,394评论 1 310
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,952评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,852评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,409评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,483评论 3 341
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,615评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,303评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,979评论 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,470评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,571评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,041评论 3 377
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,630评论 2 359

推荐阅读更多精彩内容