面试题答案
一键面试导出模块
- exports对象:在Node.js模块中,
exports
是一个空对象,它被用来向外部暴露模块的接口。通过给exports
对象添加属性的方式来导出变量、函数等。例如:
// module.js
exports.add = function(a, b) {
return a + b;
};
- module.exports:
module.exports
才是真正被导出的对象。exports
实际上是对module.exports
的一个引用。如果直接给exports
赋值一个新对象,会切断与module.exports
的联系。而直接对module.exports
赋值则可以导出任意类型的数据,如对象、函数等。例如:
// module.js
module.exports = function() {
console.log('This is a function exported by module.exports');
};
导入模块
使用require
函数来导入模块。require
函数接受一个模块标识符作为参数,这个标识符可以是核心模块(如http
、fs
等),也可以是自定义模块的相对路径(以./
或../
开头)或绝对路径,还可以是安装在node_modules
目录下的第三方模块名。例如:
// main.js
const add = require('./module.js').add;
const func = require('./module.js');
console.log(add(2, 3));
func();
模块作用域
- 独立作用域:每个Node.js模块都有自己独立的作用域。在模块内部定义的变量、函数等,默认情况下在模块外部是不可见的,不会污染全局作用域。例如:
// module.js
let localVar = 'This is a local variable';
function localFunc() {
console.log('This is a local function');
}
// 这里的localVar和localFunc在模块外部无法直接访问
- 通过导出暴露:只有通过
exports
或module.exports
导出的内容才能在其他模块中被访问,这样保证了模块之间的独立性和安全性。