introduction
In the development process, we often see Object.assign or Object Spread, both of which can help you get the object you want. Some people like to use Object.assign, some people like to use Object Spread, so which one is better? This article is to explore this question.
What Object.assign has in common with Object Spread
Function
All can implement copy of object's own attributes (including Symbol attributes).
Example
Create MyClass
class BaseClass {
foo() { return 1; }
}
class MyClass extends BaseClass {
bar() { return 2; }
}
const obj = new MyClass();
obj.baz = function() { return 3; };
obj1[Symbol.for('test')] = 4;
Use Object Spread
const clone1 = { ...obj1 };
console.log(clone1); // { baz: [Function], [Symbol(test)]: 4 }
console.log(clone1.constructor.name); // Object
console.log(clone1 instanceof MyClassTwo); // false
Use Object.assign
const clone2 = Object.assign({},obj1)
console.log(clone2); // { baz: [Function], [Symbol(test)]: 4 }
console.log(clone2.constructor.name); // Object
console.log(clone2 instanceof MyClassTwo); // false
Summarize
If the ---9605d4ab4722f659a3eeb3821c79e4e4--- of MyClass
or BaseClass
properties
assigned to the new object, only the object's own attributes (including the Symbol attribute) are copied.
Difference between Object.assign and Object Spread
Object.assign triggers object setters, Object Spread does not
Trigger target object setters
:
class MyClassOne{
set name(value){
console.log('set name:', value);
}
}
const obj = new MyClassOne();
Object.assign(obj, { name:'hahah'}); // Prints "set name: hahah"
const newObj = {...obj,{name:'hahah'}}// Does **not** print
Trigger Object.prototype setters
:
Object.defineProperty(Object.prototype, 'myProp', {
set: () => console.log('Setter called');
});
const obj = { myProp: 42 };
Object.assign({}, obj); // Prints "Setter called"
const newObj = { ..obj }; // Does **not** print "Setter called"
Alternative implementation
Object.assign({}, obj)
equals {...obj}
Compatibility comparison
Summarize
Since Object.assign
modifies the original object, it will trigger the setters
of the original object. And Object Spread
just made a shallow copy, it will not trigger setters
.
Summarize
- Both of these methods are ECMAScript specification methods and can be used with confidence.
-
Object.assign
compatibility will be better,Object Spread
compatibility is not bad. - In today's days when compatibility is easy to handle, in order to avoid accidental triggering
setter
, it is a better choice to use Object Spread all.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。