NodeJS多层嵌套函数调用时报错getScreenDevices is not a function如何解决
报错原因与修复方案
报错原因
你的实现不符合预期调用逻辑的核心问题有两点:
getLocalGraphicsEnvironment方法没有显式返回值,执行后默认返回undefined,你赋值给gEnv变量的就是undefined,调用不存在的getScreenDevices方法自然会抛出异常- 方法内部给
this挂载getScreenDevices的逻辑,实际是把方法挂载到了GraphicsEnvironment对象本身,没有给到gEnv变量,完全不符合你要的链式调用设计。
修复代码
直接让getLocalGraphicsEnvironment返回携带getScreenDevices方法的对象即可,符合你的调用逻辑:
const GraphicsEnvironment = { getLocalGraphicsEnvironment: function () { // 此处可添加你需要的初始化逻辑 return { getScreenDevices: function () { const someValue = []; // 替换为你实际的屏幕设备返回逻辑 return someValue; } } } }
修复后你的原调用代码可以正常执行:
var gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment(); var gDev = gEnv.getScreenDevices(); // 正常获取返回值,无报错
内容的提问来源于stack exchange,提问作者John Smith
相关产品推荐
相关产品推荐

