关于Node.js的作用域,写一点点东西,大牛自觉略过
发布于 11 年前 作者 bigmusic 6452 次浏览 最后一次编辑是 8 年前

在前端的JavaScript中,我们都不会把变量暴露在全局,比如jQuery,在全局只注册了一个$对象. 众所周知我们都会用匿名函数把私有变量限制在一个私有作用域,必要时才会在全局注册一个对象,比如jQuery的思路

(function(w,u){
    //var something and function something
    w.$=someObject;
})(window,undefined);

但在Node.js中,对于我这样的初学者,关于作用域的说明实在有点少,比如模块化的概念,令初学者对整个app的作用域逻辑感觉混乱,且别说Callback和和异步编程思路.还有就是运行了Node后没有类似Chrome的Console,这个是最晕的,比如检查一下究竟变量有没暴露在全局.好在有repl,这些问题都得以解决.

首先,我会想象Node.js运行一个app.js,都会用匿名函数把整个App.js的代码私有化,除非在代码中显式地申明(或是没有var)这个是全局对象(废话),当然我们不用自己写这个匿名函数,或者说运行Node app.js时,可以理解成app.js()

其次,module间的变量/对象是不可见的,只能够通过exports传递,就是说,我们不能把模块理解成app.js这个匿名函数里创建的一个对象(函数也是对象).

/**
 * Created with JetBrains WebStorm.
 * User: BiG
 * Date: 5/13/13
 * Time: 6:06 PM
 * To change this template use File | Settings | File Templates.
 */
//this is app.js
global.globalApp = 'this is global var';
var appjsVar = "this is from app";
    exports.outAppjs = appjsVar; //如果把这句写在require后,module将得不到outAppjs
var modulejs = require('./module'),
    modulejsDo = modulejs.doSome(2),
    repl = require('repl');

console.log(appjsVar);
console.log(globalApp);
console.log(modulejs.fromModule);
console.log(modulejsDo);
console.log(modulejs.backToAppjs);
repl.start('>');

//this is module.js
var inModule = "this is from module",
    fromAppjs = require('./app');
exports.fromModule = inModule;
exports.doSome = function (e) {
    var a, b, c;
    a = b = e;
    c = 'this is from module.dosome,and the result is ' + (a + b);
    return c;
};
exports.backToAppjs = fromAppjs.outAppjs + ' WARN:is is from appjs to module,and back to appjs';

其实无论app.js,还是module.js,其作用域全部是私有的…我在app.js的局部变量想让module.js知道,我只能通过exports传过去,而且必须把export写在require前,否则require了,变量其实还没过去…

以下是结果

this is from app
this is global var
this is from module
this is from module.dosome,and the result is 4
this is from app WARN:is is from appjs to module,and back to appjs
>

感谢repl哈哈,这种方式和Chrome很相似

1 回复

果然还是看不懂… 我理解的话, 模块化就是为了将大问题分解成想不相干的小问题, 模块和模块不能直接相互访问很正常吧

回到顶部