简体   繁体   English

如何使用Object.assign仅克隆属性?

[英]How to clone only properties with Object.assign?

I am trying to send a message whose content is derived from a Javascript proxy, and the postMessage() method fails except when I manually copy the the properties of my proxy on a new object: 我试图发送一条消息,其内容是从Javascript代理派生的,而postMessage()方法失败,除非是在新对象上手动复制代理的属性时:

Failed to execute 'postMessage' on 'Window': [object Object] could not be cloned.]

However, if I manually assign all the fields through boilerplate code like so 但是,如果我通过样板代码手动分配所有字段,例如

 var b = {};
 b.myField = a.myField;

the postMessage works fine. postMessage可以正常工作。 What I was expecting is that the following would have worked fine too: 我期望的是,以下内容也可以正常工作:

var b = Object.assign({},a);

but in this case it fails with the same message. 但在这种情况下,它会失败,并显示相同的消息。 Why is Object.assign cloning properties and how can I debug the cloning error? 为什么是Object.assign克隆属性,如何调试克隆错误?

I had issues with Object.assign in Lightning too. 我在Lightning中也遇到了Object.assign的问题。 I did good, using: 我做得很好,使用:

var b = JSON.parse(JSON.stringify(a));

My issue back then was, that Object.assign({},a) made a clone by reference and not by value. 当时我的问题是, Object.assign({},a)通过引用而非值进行克隆。 (I know this only answers the second part of your question, but maybe you can use it as a workaround so far) (我知道这只能回答您问题的第二部分,但到目前为止您也许可以将其用作解决方法)

I just read you are using a Window function. 我刚刚读到您正在使用Window函数。 Be aware, that the window object is a wrapper object in lightning due to the locker service 请注意,由于更衣室服务 ,窗口对象是闪电中的包装对象。

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

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