简体   繁体   English

Object.assign 和 just assign 的区别

[英]Difference between Object.assign and just assign

I would like to know the difference between this:我想知道这之间的区别:

Object.assign(otherObject, {
  someNewProperty: ''
});

and

otherObject.someNewProperty = '';

And.. which one is faster?而且..哪个更快?

Thanks.谢谢。

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. Object.assign()方法用于将所有可枚举自身属性的值从一个或多个源对象复制到目标对象。 It will return the target object. 它将返回目标对象。

Whereas otherObject.someNewProperty = ''; otherObject.someNewProperty = ''; is a method to directly assign a value to some property of an object. 是一种直接为对象的某个属性赋值的方法。

Obviously the Object.assign pattern is much slower : jsperf.com/assign-vs-equals 显然, Object.assign模式要慢得多: jsperf.com/assign-vs-equals

For single property, direct assignment (otherObject.someNewPropertie = '') is twice faster, but for multiple values - time will grow. 对于单个属性,直接赋值(otherObject.someNewPropertie ='')快两倍,但对于多个值 - 时间会增长。 Each property +5-10%. 每个属性+ 5-10%。 Also, code-wise Object.assign is nicer for multiple options. 此外,代码方式的Object.assign对于多个选项更好。

Object.assign(otherObject, {
  prop1: '',
  prop2: '',
  prop3: '',
  ...
});

VS VS

otherObject.prop1 = '';
otherObject.prop2 = '';
otherObject.prop3 = '';
...

You simply can run Profiles tab in Chrome Development tool and run few tests. 您只需在Chrome开发工具中运行“个人档案”标签,然后运行一些测试。

Object.assign() is a pretty versatile function that is designed to do complex object composition. Object.assign()是一个非常通用的函数,旨在执行复杂的对象组合。

The property dot notation is a straight forward way to assign a single value to a single property. 属性点表示法是将单个值分配给单个属性的直接方式。

Regarding which is faster, that's irrelevant considering these are not equivalent, and as one of my all time favorite posts noted " asking which one runs faster is maybe a non-starter ". 关于哪个更快,这是不相关的,考虑到这些并不相同,并且作为我最喜欢的帖子之一,注意“ 询问哪一个运行得更快可能是非首发 ”。

There is another important thing to show here about the differences between assign directly and using Object.assign(actually, not exactly a difference, but a important thing to be aware).关于直接分配和使用 Object.assign 之间的区别,这里还有另一件重要的事情要展示(实际上,不完全是区别,但需要注意的重要一点)。

If you have a Object that's assigned to another variable in JS, like this:如果你有一个对象被分配给 JS 中的另一个变量,像这样:

const a = { a: 1 }
const b = a

This is actually a good question: We just found a bug, where we would assign properties to a file using Object.assign.这实际上是一个很好的问题:我们刚刚发现了一个错误,我们会使用 Object.assign 将属性分配给一个文件。

const file = new File(["foo"], "foo.txt", {
  type: "text/plain",
});
file.name='test'; // does not update the readonly value but doesn't return an error
Object.assign(file,{name:'test'}); // error: 'Cannot set property name of #<File> which has only a getter'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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