// **.ts
function a() {
console.log(this);
}
a();
执行命令 ts-node **.ts
正常输出this
// **.ts
import './**'
function a() {
console.log(this);
}
a();
执行命令 ts-node **.ts
输出undefined
这是为什么?可以避免吗?
// **.ts
function a() {
console.log(this);
}
a();
执行命令 ts-node **.ts
正常输出this
// **.ts
import './**'
function a() {
console.log(this);
}
a();
执行命令 ts-node **.ts
输出undefined
这是为什么?可以避免吗?
当你使用 import './**'
,你实际上是在尝试导入当前目录下的所有模块。这在你尝试导入的文件中可能不会产生预期的效果,因为 this
的值取决于函数被如何调用。
在JavaScript中,this
的值在函数被调用时决定,而不是在函数被创建时决定。在严格模式下,如果函数是单独调用的,那么 this
的值就是 undefined
。
在你的例子中,a
函数被单独调用,所以 this
的值是 undefined
。你可以通过将 a
函数绑定到一个特定的对象上,来避免这个问题。例如:
// **.ts
import { bind } from 'lodash'; // lodash 是 JavaScript 实用程序库
function a() {
console.log(this);
}
const boundA = bind(a, { name: 'boundA' }); // 将 a 绑定到一个有 name 属性的对象上
boundA(); // 输出: { name: 'boundA' }
如果你想要更深入地了解 this
在JavaScript中的工作原理,我建议你阅读一些关于该主题的书籍或教程。
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答5.2k 阅读✓ 已解决
1 回答3.4k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
两个点,涉及到
esm
和strict mode
import
则代表这是一个 es module,会自动开启strict mode
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Refer...
strict mode
下,没有指定 this 的函数中,this 值为undefined
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Refer...