nodejs 中的this, __dirname,__filename问题

博客深入探讨了在Node.js中`this`、`__dirname`和`__filename`的概念。文章指出,`require`函数返回的是`module.exports`,`this`指针在该情境下关联于原始的`module.exports`。当`module.exports`被重新赋值时,`this`不再指向更新的对象。同时,`__dirname`和`__filename`实际上是`require`函数内部函数的参数,分别对应`module.path`和`module.filename`,属于`module`对象的属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

console.log("当前模块路径:", __dirname);
console.log("当前模块文件:", __filename);
exports.c = 3;
module.exports = {
  a: 1,
  b: 2
};
this.m = 5;

console.log(this === exports);  false

原因是require函数最终返回的是module.exports,这里的this指向的是最初的module.exports
require函数内部原理大致是:

 function require(modulePath) {
  //1. 将modulePath转换为绝对路径:D:\repository\NodeJS\源码\myModule.js
   //2. 判断是否该模块已有缓存
  if(require.cache["D:\\repository\\NodeJS\\源码\\myModule.js"]){
      return require.cache["D:\\repository\\NodeJS\\源码\\myModule.js"].result;
   }

//   //3. 读取文件内容
//   //4. 包裹到一个函数中
     //这里__dirname, __filename就是temp函数的参数而已
   function __temp(module, exports, require,  __dirname, __filename) {
    console.log("当前模块路径:", __dirname);
   console.log("当前模块文件:", __filename);
    exports.c = 3;
     module.exports = {
       a: 1,
      b: 2
     };
     this.m = 5;   }

   //6. 创建module对象
   module.exports = {};
   const exports = module.exports;

   __temp.call(module.exports, module, exports, require, module.path, module.filename){
    return module.exports;
 }

 require.cache = {};

const result = require("./myModule");
console.log(result);

而代码

module.exports = {
  a: 1,
  b: 2
};

module.exports被重新赋值了,新开辟了一块内存,所以this不等于现在的module.exports

__dirname, __filename就是require函数内部的一个函数的参数而已,__dirname=module.path, __filename=module.filename,都是module中的一个属性
转载自渡一教育

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值