传递私有变量作为参数时Path.join抛出异常问题排查
问题根源:回调函数中的
this指向错误 你遇到的其实是JavaScript/TypeScript里非常经典的函数this指向绑定坑——当你把this.onReady作为回调传给app.on('ready', ...)时,这个函数内部的this已经不再指向你的Main类实例了!
具体拆解问题
在你的非可用代码里:
this.app.on('ready', this.onReady)
这里传递的this.onReady只是一个单纯的函数引用,当Electron的app触发ready事件调用它时,函数内部的this会默认指向触发事件的对象(也就是app实例),而不是你创建的Main类实例。这时候this.indexFilePath自然就是undefined,把undefined传给Path.join肯定会抛出异常。
而用字符串字面量'index.html'的时候,不需要依赖this获取变量,所以完全不受影响,能正常运行。
三种实用解决方案
1. 在构造函数中用bind绑定this
修改构造函数里的事件绑定,强制把onReady的this绑定到当前类实例:
constructor (app: Electron.App) { this.app = app this.browserWindow = new None() // 绑定this到当前Main实例 this.app.on('ready', this.onReady.bind(this)) }
2. 用箭头函数包裹回调
箭头函数会自动继承外层作用域的this,直接把回调写成箭头函数形式:
constructor (app: Electron.App) { this.app = app this.browserWindow = new None() this.app.on('ready', () => this.onReady()) }
3. 把onReady定义为类箭头方法
直接在类里用箭头函数定义方法,这样方法的this会永久绑定到类实例,最简洁省心:
// 修改onReady的定义方式 private onReady = (): void => { this.browserWindow = new Some(new Electron.BrowserWindow({ width: 800, height: 600 })) this.browserWindow.unwrap().loadFile(Path.join(__dirname, this.indexFilePath)) }
从编译后的代码验证问题
你贴出的编译后JS代码也能佐证这个问题:
this.app.on('ready', this.onReady);
这里的this.onReady没有做任何绑定处理,运行时onReady里的this必然不是Main实例,this.indexFilePath就是undefined,最终导致Path.join报错。
别太焦虑啦,这种this指向问题是几乎所有JS/TS开发者都踩过的坑,踩过一次就再也忘不掉了😉
内容的提问来源于stack exchange,提问作者strokeberry
相关产品推荐
相关产品推荐

