简体   繁体   中英

ES6 Object.assign(): why do undefined properties override defined properties?

Why does the following snippet return { a: 3, b: undefined } and not { a: 3, b: 2 } ?

 console.log(Object.assign({ a: 1, b: 2 }, { a: 3, b: undefined })); 

This question asks about a function that gives the latter output instead of the former, but my question is why was Object.assign() designed this way? Or to put it a different way, what exactly are the differences between { a: 3 } and { a: 3, b: undefined } ?

UPDATE (from the comments on apsillers answer):

{ a: 1 } says "I have no property named 'b'", { a: 1, b: undefined } says "I have a property 'b' but it has not yet been given a value", and { a: 1, b: null } says "I have a property 'b' that should hold an object but has not yet been given an object to hold". Since in the latter two the object has a property 'b', regardless of what the value is, it will still override non-null non-undefined values when passed into Object.assign() .

{ a: 3 } has one property, whose key is the string " a ". You can observe this by Object.keys({a:3}) , which returns ["a"] .

{ a: 3, b: undefined } has two properties, one called a and another called b . Calling Object.keys({a: 3, b: undefined}) returns ["a", "b"] .

Object.assign uses values from whatever (enumerable) properties exist on each incoming object, and assign 's specification does not handle specially the case where a property happens to have the value undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM