简体   繁体   English

带布尔值的Object.assign

[英]Object.assign with boolean

Whats the difference between 之间有什么区别

Object.assign({},obj1,obj2);

and

Object.assign(true,obj1,obj2);

I know what obj.assign does but whats the use of the latter one ? 我知道obj.assign做什么,但是后者的用途是什么? it returns a boolean type with obj1 and obj2 to merged into it. 它返回带有obj1和obj2的布尔类型以合并到其中。

PS: It was an interview question so would like to know whats the use case of this. PS:这是一个面试问题,所以想知道它的用例是什么。

As outlined above, primitives get "boxed", so the following: 如上所述,基元被“装箱”,因此如下所示:

 Object.assign(true, obj1, obj2)

is merely the same as: 仅与以下内容相同:

 const bool = Object.assign(new Boolean(true), obj1, obj2)

now boolean objects are just regular objects, that return a boolean when valueOf() is called on them. 现在,布尔对象只是常规对象,在对它们调用valueOf()时返回布尔值。 That means you get some funny behaviour: 这意味着您会得到一些有趣的行为:

 bool === true // false
 bool == true // true
 +bool === 1 // true

You cannot even use that Boolean object inside conditions as all objects are truthy: 您甚至不能在条件内使用该布尔对象,因为所有对象都是真实的:

  if(Object.assign(false,{a: 1 }))
   alert("works");

So actually there is no difference between a regular object and a Boolean object, except that the latter adds some confusion and serves no purpose whatsoever. 因此,实际上,常规对象和布尔对象之间没有区别,只是布尔对象增加了一些混乱,并且毫无用处。

Besides boolean is supposed to be primitive type it has object-type wrapper that is... surprise Boolean. 除了布尔值应该是原始类型之外,它还具有对象类型包装器,这是...令人惊讶的布尔值。

In case of 的情况下

Object.assign(true,{a: 1}, {b: 2})

there is such boxing(term from Java/C# worlds I really like) happens. 有这样的拳击(我真的很喜欢Java / C#世界的术语)发生了。 And then Object.assign works over this object-type wrapper as it should. 然后, Object.assign处理此对象类型的包装器。 That's why result looks in console like 这就是为什么结果在控制台中看起来像

Boolean {true, a: 1, b: 2} 布尔值{true,a:1,b:2}

Boolean's object like every other objects can be extended with custom keys/values. 像其他所有对象一样,布尔对象也可以使用自定义键/值进行扩展。 Output looks confusing but if you expand this in console you will see there is no actually "value of true without any key" - so it's just tricky output. 输出看起来令人困惑,但是如果在控制台中扩展它,您将看到实际上没有“没有任何键的true值”-因此,这只是棘手的输出。

BTW exactly the same happens to strings when you tries to call some method on primitive value like 顺便说一句,当您尝试在原始值上调用某些方法时,字符串完全一样

'12345'.split(/./)

It is converted into object with String() constructor and then call String's method. 它使用String()构造函数转换为对象,然后调用String的方法。

And yes, I believe it should be never used in real life code. 是的,我相信现实生活中不应使用它。

Here is spec says : 这是规格说

  1. Let to be ToObject(target). 设为ToObject(target)。

So explicit converting primitive-to-object is very first step. 因此,显式将原语转换为对象是第一步。

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

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