Reputation: 460
I'm developing an Electron app in which I need to send an array containing objects of a given class trough the ipcRenderer
and I've noticed those objects lose all of their prototype data on doing so. For example:
//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' }
})
This is particularly important to me because after that there's point in which I need to check if all elements of that array are instances of that particular class:
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}
})
Is this intended behavior? If so, what is the most appropriate approach for dealing with this kind of problem?
Upvotes: 1
Views: 881
Reputation: 4641
https://electronjs.org/docs/api/ipc-renderer#ipcrenderersendchannel-arg1-arg2-
Arguments will be serialized in JSON internally and hence no functions or prototype chain will be included.
IPC only accepts serializable object. There is no easy, out of box way to compare instance between processes, since it already crossed boundary of runtime context it doesn't have lot meaning to compare instance. You may need design in other way doesn't rely on instance types.
Upvotes: 5