無標題文章

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)

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子厚脉,更是在濱河造成了極大的恐慌凡泣,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,110評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異庇绽,居然都是意外死亡抹恳,警方通過查閱死者的電腦和手機员凝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來奋献,“玉大人健霹,你說我怎么就攤上這事∑柯欤” “怎么了糖埋?”我有些...
    開封第一講書人閱讀 165,474評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長窃这。 經(jīng)常有香客問我瞳别,道長,這世上最難降的妖魔是什么杭攻? 我笑而不...
    開封第一講書人閱讀 58,881評論 1 295
  • 正文 為了忘掉前任祟敛,我火速辦了婚禮,結果婚禮上兆解,老公的妹妹穿的比我還像新娘馆铁。我一直安慰自己,他們只是感情好锅睛,可當我...
    茶點故事閱讀 67,902評論 6 392
  • 文/花漫 我一把揭開白布埠巨。 她就那樣靜靜地躺著,像睡著了一般现拒。 火紅的嫁衣襯著肌膚如雪乖订。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,698評論 1 305
  • 那天具练,我揣著相機與錄音乍构,去河邊找鬼。 笑死,一個胖子當著我的面吹牛哥遮,可吹牛的內(nèi)容都是我干的岂丘。 我是一名探鬼主播,決...
    沈念sama閱讀 40,418評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼眠饮,長吁一口氣:“原來是場噩夢啊……” “哼奥帘!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起仪召,我...
    開封第一講書人閱讀 39,332評論 0 276
  • 序言:老撾萬榮一對情侶失蹤寨蹋,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后扔茅,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體已旧,經(jīng)...
    沈念sama閱讀 45,796評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,968評論 3 337
  • 正文 我和宋清朗相戀三年召娜,在試婚紗的時候發(fā)現(xiàn)自己被綠了运褪。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,110評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡玖瘸,死狀恐怖秸讹,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情雅倒,我是刑警寧澤璃诀,帶...
    沈念sama閱讀 35,792評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站蔑匣,受9級特大地震影響文虏,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜殖演,卻給世界環(huán)境...
    茶點故事閱讀 41,455評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望年鸳。 院中可真熱鬧趴久,春花似錦、人聲如沸搔确。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽膳算。三九已至座硕,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間涕蜂,已是汗流浹背华匾。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留机隙,地道東北人蜘拉。 一個月前我還...
    沈念sama閱讀 48,348評論 3 373
  • 正文 我出身青樓萨西,卻偏偏與公主長得像,于是被迫代替她去往敵國和親旭旭。 傳聞我的和親對象是個殘疾皇子谎脯,可洞房花燭夜當晚...
    茶點故事閱讀 45,047評論 2 355

推薦閱讀更多精彩內(nèi)容