在下面的代码中,与forEach循环一起使用的回调函数遍历返回的结果。forEach循环中的变量“错误”和回调中的“错误”是否相同?
session.getAll(options, function (error, varbinds) {
varbinds.forEach(function (vb) {
if (error)
console.log('getALL Fail ');
else
console.log(vb.value);
});
});
Run Code Online (Sandbox Code Playgroud)
是的,它是相同的变量。
我不确定你知道多少。因此,我将详细解释。JavaScript的作用域在功能级别*。将功能定义视为树上的点。树上的每个点都是一个作用域。使用变量时,只能使用当前作用域中的变量以及祖先可用的任何变量(最高范围)(全局作用域)。以下是一些规则和示例,可以帮助您更好地理解:
*更新:ES6 const和let处于块级别
内部函数可以访问外部函数级别的变量
function a() {
var a = 4;
function b() {
alert(a); /* a = 4 */
}
}
Run Code Online (Sandbox Code Playgroud)
参数的定义范围与在下面一行定义的范围相同
function a(a) {
// variable "a" is at same scope as the example above
function b() {
alert(a);
}
}
Run Code Online (Sandbox Code Playgroud)
相邻函数中的变量不可访问
函数a()是父项。b()和c()是其子级。这些孩子无法访问彼此的变量。
function a() {
function b() {
var aValue = 2;
}
function c() {
alert(aValue); /* "aValue" is undefined here */
}
}
Run Code Online (Sandbox Code Playgroud)
函数定义的位置很重要
如果运行,则返回5 main();:
function getValue(returnFunc) {
var a = 7;
alert(returnFunc());
}
function main() {
var a = 5;
getValue(function() { return a; }); // anonymous function becomes "returnFunc"
}
Run Code Online (Sandbox Code Playgroud)
最后,变量覆盖
(function getValue() {
var a = 5;
(function () {
var a = 7;
alert(a);
})();
alert(a);
})();
Run Code Online (Sandbox Code Playgroud)
在这些示例中,我尝试避免使用自调用函数/ IIFE,但是我对最后一个示例不由自主。我认为这是最简单的方法。运行此命令,将得到7,然后是5。但是,如果在内部“ a”上排除“ var”,则...
(function getValue() {
var a = 5;
(function () {
a = 7;
alert(a);
})();
alert(a);
})();
Run Code Online (Sandbox Code Playgroud)
您将得到7、7。这是因为“ var”在内存中创建了一个新空间。同样,如果名称与更高范围的内容发生冲突,则它会被覆盖为其他变量(尽管名称相同)。
有关更多示例,请参见:JavaScript中变量的范围是什么?
是的,它是同一个变量,如果您error使用关键字在 forEach 回调范围内定义另一个变量,它会发生变化var:
session.getAll(options, function (error, varbinds) {
varbinds.forEach(function (vb) {
if (error) //Same error as the error parameter above
console.log('getALL Fail ');
else
console.log(vb.value);
});
});
session.getAll(options, function (error, varbinds) {
varbinds.forEach(function (vb) {
var error = false; //New error for this closure.
if (error)
console.log('getALL Fail ');
else
console.log(vb.value);
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9621 次 |
| 最近记录: |