【问题标题】:Electron - Loss of prototype data on ipcRenderer.send()Electron - ipcRenderer.send() 上的原型数据丢失
【发布时间】:2018-07-12 22:58:33
【问题描述】:

我正在开发一个 Electron 应用程序,在该应用程序中,我需要通过 ipcRenderer 发送一个包含给定类对象的数组,并且我注意到这些对象在这样做时会丢失所有原型数据。例如:

//js running on the browser
const {ipcRenderer} = require('electron');
class Thingy {
   constructor() {
      this.thingy = 'thingy'
   }
}
let array = [new Thingy(), 'another thing']
console.log(array[0] instanceof Thingy) // => true
console.log(array[0].constructor.name) // => 'Thingy'
console.log(array[0]) // => Thingy { this.thingy='thingy' }
ipcRendered.send('array of thingys', foo)

//app-side js
const {ipcMain} = require('electron');
ipcMain.on('array of thingys', (event, array) => {
    console.log(array[0] instanceof Thingy) // => false
    console.log(array[0].constructor.name) // => 'Object'
    console.log(array[0]) // => Object { this.thingy='thingy' }
})

这对我来说特别重要,因为在那之后我需要检查该数组的所有元素是否都是该特定类的实例:

ipcMain.on('array of thingys', (event, array) => {
    //if the array only contains objects of the class Thingy
    if (array.filter((elm) => {return !(elm instanceof Thingy)}).length == 0) {
        //do some stuff
    } else {//do some other stuff}
})

这是预期的行为吗?如果是这样,处理此类问题最合适的方法是什么?

【问题讨论】:

    标签: javascript class oop electron prototype


    【解决方案1】:

    https://electronjs.org/docs/api/ipc-renderer#ipcrenderersendchannel-arg1-arg2-

    参数将在内部以 JSON 序列化,因此不会包含任何函数或原型链。

    IPC 只接受可序列化的对象。比较进程之间的实例没有简单的、开箱即用的方法,因为它已经越过了运行时上下文的边界,比较实例没有太多意义。您可能需要以其他方式进行设计,而不依赖于实例类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      • 2013-08-31
      • 2012-11-07
      • 2010-11-19
      • 2020-07-02
      相关资源
      最近更新 更多