简体   繁体   English

在Javascript中(使用node.js时),您如何知道/定义变量的范围?

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

If I define something in a passed function, eg 如果我在传递的函数中定义某些内容,例如

var name = "Whatever";

Is this now accessible from other parts of the application, or is it limited? 现在可以从应用程序的其他部分访问它,还是受限制? What's the logic behind defining scope in node.js javascript? 在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. name变量将只可在其被创建的功能,或者在嵌套在该函数的功能。

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 . 它的原始可变环境随身携带,无论环境在哪里,该环境之外的任何代码都无法访问name

Any variable defined in a method is only available in that method, if you use var . 如果使用var ,则方法中定义的任何变量仅在该方法中可用。 If you do 如果你这样做

myVar = 1;

myVar will be global. myVar将是全球性的。

Node is like other javascript. 节点就像其他JavaScript。 Node does define a global variable, so you can do things like Node确实定义了global变量,因此您可以执行以下操作

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. 由于节点是异步的,因此最终会定义很多回调。 ie 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. 完成后,传入的函数将由someMethod调用。 Let's say you invoked someModule.someMethod in a function. 假设您在函数中调用了someModule.someMethod 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. 我建议您花一些时间阅读有关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 ;) 您应该阅读有关闭包的内容;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM