简体   繁体   English

如果 function 作为“目标”参数传递,Object.assign output 是否不同

[英]Does Object.assign output differ if a function is passed as the 'target' param

I have the following code, that executes successfully, but I am not quite sure how can this happen.我有以下代码,可以成功执行,但我不太确定这怎么会发生。

 var obj = Object.assign( (...args) => ({ a: 1 }), { toString: () => 'type' } ); console.log(obj); // f type

Why is the output of the above not为什么上面的output不是

{ 
  f: () => {
    return {a: 1}
  }, 
  toString: () => 'type'
}

Could someone give a detailed explanation of the above?有人可以对上述内容进行详细解释吗?

Object.assign copies the values of all the enumerable own properties of several source objects to a target object: Object.assign将多个源对象的所有可枚举自身属性的值复制到目标 object:

Object.assign({ a: 'foo' }, { b: 'bar' });
// => { a: 'foo', b: 'bar' }

In your given example the target object is the arrow function.在您给定的示例中,目标 object 是箭头 function。 In Javascript, functions are just objects (with their own enumerable properties) and you can add additional properties without worry.在 Javascript 中,函数只是对象(具有自己的可枚举属性),您可以放心地添加其他属性。

The source object in your example is an object containing a property toString with a function value.在您的示例中,源 object 是一个 object,其中包含一个toString属性,其值为 function。 You're essentially copying this property onto the destination function.您实际上是将这个属性复制到目标 function 上。

When you console.log the resulting object, toString is automatically called and its result is logged to the console.当您console.log生成 object 时,会自动调用toString并将其结果记录到控制台。 Since the object is actually a function you will see the weird output of f type .由于 object 实际上是 function 你会看到f type奇怪output 。 How this is shown is browser dependent though.但是,如何显示取决于浏览器。

To answer your question as to why the returned object doesn't look like what you wrote: You extended the function itself.要回答您关于为什么返回的 object 看起来不像您所写的问题:您扩展了 function 本身。 If you instead created a new object with property f to the given function you would get the desired result:如果您改为创建一个新的 object,其属性f为给定的 function,您将获得所需的结果:

 const obj = Object.assign({ f: (...args) => ({ a: 1 })}, { toString: () => 'type' }); console.log(obj);

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

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