我正在使用 window.postMessage 将对象从父窗口传输到 iframe。然而,当我们在 iframe 上接收对象时,该对象会丢失proto。有没有办法解决这个问题
最佳答案
Window.postMessage
使用结构化克隆算法通过递归克隆在边界之间传递对象。它具有局限性,如 MDN page 中所述。
根据 documentation某些对象属性不会保留:
- The lastIndex property of RegExp objects is not preserved.
- Property descriptors, setters, getters, and similar metadata-like features are not duplicated. For example, if an object is marked readonly with a property descriptor, it will be read/write in the duplicate, since that's the default.
- The prototype chain is not walked or duplicated.
解决方法:
将原型(prototype)链作为对象与数据/有效负载一起发送,并使用Object.create
或Object.setprototypeof
接收端的方法来纠正接收到的对象的原型(prototype)。
关于javascript - 当我们通过 iframe 传输对象时,我们可以保留 __proto__ 吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60751313/