NodeJS中对象箭头函数方法的this指向为空对象问题
为什么箭头函数中的this指向空对象,而非预期的配置对象?
这个问题的核心在于箭头函数的this绑定规则和普通函数完全不同,你踩了箭头函数的常见坑之一!
原因详解
箭头函数不会创建属于自己的this上下文,它会捕获定义时所在作用域的this值,而不是调用时的this。在你的代码里:
getLogPath和getHtmlPath是用箭头函数定义的,它们在spctrConfiguration对象字面量内部被创建,此时箭头函数所在的外层作用域是Node.js模块的顶层作用域,这个作用域的this初始指向module.exports(此时还是一个空对象,因为你之后才把spctrConfiguration赋值给它)。- 当你在
index.js中调用spctrConfiguration.getLogPath()时,箭头函数并不会因为是对象方法调用就改变this指向,它依然保持着定义时捕获的空对象,所以this.dataPath自然就是undefined,导致报错。
而如果是普通函数作为对象方法,调用时this会自动指向调用它的对象(也就是spctrConfiguration),这才是你原本期望的行为。
解决方案
把箭头函数改成普通函数即可,有两种写法可选:
写法一:传统函数表达式
const path = require('path'); // 别忘了先引入path模块,否则path.join会报错 let spctrConfiguration = { dataPath: '/data/', mongoDB: 'datadb', mongoHost: 'mongo', mongoPort: 27017, redisHost: 'redis', redisPort: 6379, getLogPath: function() { console.log(this); // 现在this指向spctrConfiguration return path.join(this.dataPath, 'spctrworker_logs'); }, getHtmlPath: function() { return path.join(this.dataPath, 'spctrworker_html'); } };
写法二:ES6方法简写(更简洁)
const path = require('path'); let spctrConfiguration = { dataPath: '/data/', mongoDB: 'datadb', mongoHost: 'mongo', mongoPort: 27017, redisHost: 'redis', redisPort: 6379, getLogPath() { console.log(this); // this正确指向spctrConfiguration return path.join(this.dataPath, 'spctrworker_logs'); }, getHtmlPath() { return path.join(this.dataPath, 'spctrworker_html'); } };
这样修改后,当你在index.js中调用这两个方法时,this就会正确指向spctrConfiguration,this.dataPath也能拿到正确的值了。
内容的提问来源于stack exchange,提问作者mrQWERTY
相关产品推荐
相关产品推荐

