开发者

In Javascript (when using node.js), how do you know/define the scope of variables?

If I define something in a passed function, e.g.

var name = "Whatever";

Is this now accessible from other parts of the application, or is it limited?开发者_如何学Go What's the logic behind defining scope in node.js javascript?


The name variable will only be available in the function in which it was created, or in the functions nested inside that function.

This is true irrespective of where the function is passed. It's original variable environment is carried along with it wherever it goes, and any code outside that environment will not have access to name.


Any variable defined in a method is only available in that method, if you use var. If you do

myVar = 1;

myVar will be global.

Node is like other javascript. Node does define a global variable, so you can do things like

global.SOME_CONSTANT = 'A Constant'

and then use that like

SOME_CONSTANT

anywhere in your code/modules.

Because node is asynchronous, you end up defining a lot of callbacks. i.e. you do a lot of

someModule.someMethod(opts, function(data){
   // callback code in here
});

where the function you passed in gets invoked by someMethod when it is done. Let's say you invoked someModule.someMethod in a function. If you defined a variable in that outer function, so your code looks like

var x = [];
someModule.someMethod(opts, function(data){
   // x is available in this callback because of closures, so you can do
   x.push(data);
});

the variable defined in the outer scope is available in the callback because of closures. I suggest you spend some time reading about closures in javascript.


It´s only available in the module, and only in the function it is defined. There´s no way to define the scope. Every module has its own global scope.

You should read about closures ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜