![](/style/images/good.png)
![](/style/images/bad.png)
Object.assign vs Object Spread
source link: https://www.fly63.com/article/detial/11906
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
在开发过程中,我们经常能看到 Object.assign 或 Object Spread,这两个方法都能帮助你得到想要的对象。有的人喜欢用Object.assign,有些人喜欢用 Object Spread,那么用哪一种比较好呢?这篇文章就是来探讨这个问题。
Object.assign 与 Object Spread 共同点
都可以实现 object 自有属性(包括 Symbol 属性)的 copy。
创建 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;
使用 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
使用 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
没有把 MyClass 或 BaseClass 的 properties 赋值给新的对象,说明 只拷贝了object 自有属性(包括 Symbol 属性)。
Object.assign 与 Object Spread 不同点
Object.assign 会触发对象的 setters, Object Spread 不会
触发 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
触发 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"
Object.assign({}, obj) 等于 {...obj}
兼容性对比
![62d75db40a2e2.jpg](https://api.fly63.com/vue_blog/public/Uploads/20220720/62d75db40a2e2.jpg)
![62d75db72ee8e.jpg](https://api.fly63.com/vue_blog/public/Uploads/20220720/62d75db72ee8e.jpg)
由于 Object.assign 修改了原来的对象,所以会触发原来对象的 setters。而 Object Spread 只是进行了一次浅拷贝,不会触发 setters。
- 这两个方法都是ECMAScript 规范的方法,都可以放心使用。
- Object.assign 兼容性会更好一点,Object Spread 兼容性也不差。
- 在兼容性很容易得到处理的今天,为了避免意外触发的 setter,全部使用 Object Spread` 是更好的选择。
来自:https://segmentfault.com/a/1190000042192653
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK