// exposed.
var err = new Error;
err.name = ‘Trace’;
err.message = label || ”;
Error.captureStackTrace(err, arguments.callee);
console.error(err.stack);
}
var assert = function (expression) {
if (!expression) {
var arr = Array.prototype.slice.call(arguments, 1);
require(‘assert’).ok(false, format.apply(this, arr));
}
}
通过这些函数,我们基本上知道NodeJS在全局作用域添加了些什么内容,其实Console对象上的相关api只是对Process对象上的”stdout.write“进行了更高级的封装挂在到了全局对象上。
(3),exports与module.exports
在NodeJS中,有两种作用域,分为全局作用域和模块作用域
var name = ‘var-name’;
name = ‘name’;
global.name=’global-name’;
this.name = ‘module-name’;
console.log(global.name);
console.log(this.name);
console.log(name);
我们看到var name = ‘var-name’;name = ‘name’; 是定义的局部变量;
而global.name=’global-name’;是为 全局对象定义一个name 属性,
而 this.name = ‘module-name’;是为模块对象定义了一个name 属性
那么我们来验证一下,将下面保存成test2.js,运行
var t1 = require(‘./test1’);
console.log(t1.name);
console.log(global.name);
从结果可以看出,我们成功导入 了test1 模块,并运行了 test1的代码,因为在test2 中 输出 了global.name,
而 t1.name 则是 test1 模块中通过this.name 定义的,说明this 指向 的是 模块作用域对象。
exports与module.exports的一点区别
Module.exports才是真正的接口,exports只不过是它的一个辅助工具。最终返回给调用的是
Module.exports而不是exports。所有的exports收集到的属性和方法,都赋值给了
Module.exports。当然,这有个前提,就是
Module.exports
本身不具备任何属性和方法
。
如果,
Module.exports
已经具备一些属性和方法,那么exports收集来的信息将被忽略。举个栗子:
新建一个文件 bb.js
exports.name = function() {









