问题描述
我只是想念有关“这个”的东西(考虑到我想念的那种东西,这很糟糕)。我有一个用于日志格式化的类。在仅用于调试/测试的一种方法中,“ this”原来是未定义的。我删除了几乎所有内容,仅用于演示目的。代码如下:
class LogFormatter {
constructor(source) {
// nothing relevant.
}
formatted() {
return 'returns a formatted string whatever';
}
clog(message,sub) {
console.log(this.formatted());
}
// made only for testing
showThis() {
console.log(this);
}
}
它的用法如下:
const
LogFormatter = require('log-formatter'),lgf = new LogFormatter('asd');
lgf.clog('whatever');
如果我通过this
方法访问formatted
,或者甚至通过调用showThis
,它都可以正常工作。因此,似乎与console.log
无关。
当我调用clog
方法时,将引发下一个错误:
console.log(this.formatted());
^
TypeError: Cannot read property 'formatted' of undefined
因此,仅在clog
方法中,“ this”是未定义的。那么,我面前看不见的大象是什么? :)
编辑:请注意,如果我在格式化方法内添加console.log(this),也可以正常工作。
此外,我已经注意到,如果我尝试通过LogFormatter通过这种方式创建新对象:
const
LogFormatter = new require('log-formatter')('whatever')
抛出一个异常,原因是该类是唯一通过module.exports = LogFormatter
导出的事实,因此我不能在没有新关键字AFAIK的情况下执行LogFormatter。另外,使用良好的旧构造函数语法也没有这个问题。
预先感谢:)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)