【发布时间】: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