Issue
As I know spread operator return a new object after operation:
let a = {a:1};
let b = {a: 2}
let a = {...a,...b}
So, last a is not referenced to a, it is a new object in memory.
Is it possible to use spread operator without changing initial object, I mean a reference in memory?
Solution
It's guaranteed by the 12.2.6.7 Runtime Semantics: Evaluation and 12.2.6.8 Runtime Semantics: PropertyDefinitionEvaluation that the object returned from an object literal with "spread syntax" is always a new object.
Relevant parts of the spec:
- Let
objbeObjectCreate(%ObjectPrototype%).
and
PropertyDefinition:...AssignmentExpression
1. LetexprValuebe the result of evaluatingAssignmentExpression.
2. LetfromValuebe ?GetValue(exprValue).
3. LetexcludedNamesbe a new empty List.
4. Return? CopyDataProperties(object, fromValue, excludedNames).
There is currently no other way to mutate the object other than just assigning its properties directly.
As @Heretic Monkey noted in the comments: the question is tagged as typescript while I'm answering about javascript. The thing is that TS compiler must retain the native js runtime semantics, so in this very case it's okay to refer to the ES2018 standard.
Answered By - zerkms
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.