CommonJS的本质

01.js

	this.a = 1;
	exports.b = 2;
	exports = {
	    c: 3,
	}
	module.exports = { d: 4 }
	exports.e = 5
	this.f = 6;

	console.log(this);
	console.log(exports);
	console.log(module.exports);

执行结果

{ a: 1, b: 2, f: 6 }
{ c: 3, e: 5 }
{ d: 4 }

通过require函数伪代码分析

function require(modulePath) {
    // 根据传递的模块路径,得到模块完整的绝对路径
    var moduleId = getModuleId(modulePath);
    // 判断缓存
    if (cache[moduleId]) {
        return cache[moduleId]
    }
    // 真正运行模块代码的辅助函数
    function _require(exports, require, module, __filename, __dirname) {
        // 目标模块的代码在这里 01.js
        // this.a = 1;
        // exports.b = 2;
        // exports = {
        //     c: 3,
        // }
        // module.exports = { d: 4 }
        // exports.e = 5
        // this.f = 6;
    }

    // 准备并运行辅助函数
    var module = {
        exports: {}
    }
    var exports = module.exports;
    // 得到模块文件的绝对路径
    var __filename = moduleId;
    // 得到模块所在目录的绝对路径
    var __dirname = getDirname(__filename);
    
    _require.call(exports, exports, require, __filename, __dirname)
    // 缓存module.exports
    cache[moduleId] = module.exports;
    // 返回module.exports
    return module.exports;

}

CommonJS 的本质就是将模块代码放到一个函数环境中执行,所以在模块中可以直接打印 arguments
CommonJS 中的 this === exportstrue

你可能感兴趣的:(JavaScript,node,前端)