You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS中this关键字指向疑惑:函数内this.name为何返回undefined?

NodeJS中this关键字的常见误区与你的问题解析

首先纠正一个关键认知:在NodeJS的模块文件顶层作用域中,this并非指向全局对象,而是直接指向当前模块的module.exports对象。这和浏览器环境的全局this有本质区别,也是你遇到问题的核心原因。

你的代码现象解析

1. 顶层console.log(this.name)输出Per

你在模块顶层执行console.log(this.name)时,这里的this就是module.exports——因为你之前已经给module.exports.name赋值为'Per',所以自然能输出正确的值。

2. 直接调用hello()输出undefined

NodeJS的模块默认运行在严格模式下,当你直接以普通函数形式调用hello()时,函数内部的this会被设置为undefined(而非全局对象)。因为undefined没有name属性,所以输出undefined。

3. 使用bind(module.exports)后能正常输出

Function.prototype.bind()方法会创建一个新函数,这个新函数被调用时,内部的this会被永久绑定到你传入的module.exports对象上。所以调用hello2()时,this.name就等同于module.exports.name,自然能输出'Per'。

补充说明

如果想让普通函数调用时也能拿到module.exports上的属性,除了bind,还可以用以下方式:

  • 直接在函数内部引用module.exports.name,绕开this的指向问题
  • 使用箭头函数:箭头函数的this继承自外层作用域,也就是模块顶层的this(即module.exports),比如:
    const hello = () => {
        console.log(this.name);
    }
    hello(); // 输出Per
    

内容的提问来源于stack exchange,提问作者j523

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 20:49:55