Gar*_*cia 1 javascript oop prototype class electron
我正在开发一个 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' }
})
Run Code Online (Sandbox Code Playgroud)
这对我来说特别重要,因为之后我需要检查该数组的所有元素是否都是该特定类的实例:
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}
})
Run Code Online (Sandbox Code Playgroud)
这是有意的行为吗?如果是这样,处理此类问题最合适的方法是什么?
小智 5
https://electronjs.org/docs/api/ipc-renderer#ipcrenderersendchannel-arg1-arg2-
参数将在内部以 JSON 进行序列化,因此不会包含任何函数或原型链。
IPC 只接受可序列化的对象。没有简单的开箱即用的方法来比较进程之间的实例,因为它已经跨越了运行时上下文的边界,所以比较实例没有多大意义。您可能需要以其他不依赖于实例类型的方式进行设计。
归档时间: |
|
查看次数: |
812 次 |
最近记录: |