javascript - 在 JavaScript 模块中使用 this
问题描述
我写了以下代码(模拟):
module.exports = {
test() {
console.log('test')
},
iffer(nb) {
if (nb !== 0) {
this.test()
}
}
}
我收到错误“测试不是函数”。
并尝试了以下方法:
let that = this
module.exports = {
test() {
console.log('test')
},
iffer(nb) {
if (nb !== 0) {
that.test()
}
}
}
该解决方案仍然无法正常工作,因为 JavaScript 模块默认开启了严格模式。有谁知道这个问题的解决方案?
解决方案
只是module.exports
再次参考。
iffer(nb){
if (nb !== 0) {
module.exports.test()
}
}
您也可以先将导出的对象放入独立变量中,以使其更易于引用。或者,让所有函数都是独立的以便于参考,然后导出一个包含所有函数的对象。
const test = () => console.log('test');
const iffer = (nb) => {
if (nb !== 0) {
test();
}
};
module.exports = { test, iffer };
如果您的环境与 ES6 模块语法兼容,我建议您改用它们。
export const test = () => console.log('test');
export const iffer = (nb) => {
if (nb !== 0) {
test();
}
};
推荐阅读
- ios - 如何使 VStack 在 SwiftUI 中填充屏幕的宽度
- unit-testing - Kotlin 测试 API 调用
- angular - 如何对 Rxjs combineLatest 进行单元测试?
- spring - Spring boot Hibernate 多对多关系。传递给持久化的分离实体:
- azure - 使用 JDBC 从 Pyspark 更新表
- python-3.x - 谷歌日历 API 同步
- java - 取决于 OS 类型的条件 Spring 配置属性值
- flutter - 等价于 Flutter 中 CSS 的数值型 vertical-align
- php - 在 Laravel Collective 中为选择选项设置 ID
- php - 分页 php 不工作,卡在第一个,即使我回显存储页面数据的变量是正确的