为什么 Javascript 导入函数 returns 未定义

Why Javascript import function returns undefined

我想更多地了解 javascript 参考范围,我试图从另一个文件中导入一个函数,就像这样

file1.js

exports.checkIfCan = function(){
 //make some check
}

exports.calculate = function(){
   this.checkIfCan();
}

并通过此导入使用计算方法

file2.js

const { calculate } = require('./file1.js')

calculate()

其实错误是this.checkIfCan is not a function 但是如果我像这样导入所有模块它就可以工作

const calculation = require('./file1.js')

calculation.calculate();

我只想进一步了解 javascript

中的 global/local 范围

this 指的是函数调用的上下文,在你的例子中是 undefined (在浏览器上默认是 window)。

这里举一个尽可能简单的例子让你理解:

calculation.calculate(); // <= you are calling calculate from calculation, so 'this' is calculation

calculate(); // <= you are calling calculate from... nothing, so 'this' is undefined

更新:使用箭头函数它可以在任何一种情况下工作,因为 this 将从函数的周围范围而不是上下文中获取,并且在 Node 模块的顶级代码中 this等同于 module.exports.

javascript 中关于 this 的解释很多,我可以建议您阅读免费电子书 You Don't Know JS: this and Object prototypes 吗?您会在那里找到更多信息。

您应该改用导入:

file1.js

function abc() {}

export {
   abc
}

file2.js

import { abc } from 'file1.js';
abc();

@Vlad Vlads,您的问题出在文件 file1.js.[= 中使用关键字 this 14=]

根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this,可能会发生以下行为:

The value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called.

话虽如此,如果您在函数中删除关键字 this,则以下内容将按预期工作:

const { calculate } = require('./file1.js')

calculate()

您的第二个示例也将按预期工作

const calculation = require('./file1.js')

calculation.calculate()