Javascript 闭包在作为参数传递的函数表达式中是如何工作的?
关于Javascript 闭包在作为参数传递的函数表达式中是如何工作的?,javascript,closures,Javascript,Closures,关于闭包的一件事。 在下面的两段代码中,我将函数表达式作为回调传递 (在第一段代码中)当调用函数表达式时,我希望看到匿名函数关闭def,但是当我调用second()而不是查看变量first(其中first是updatedValue)的“闭包”时,在全局变量环境中搜索并查找first,其中first的值为oldValue function def(first="oldValue" , second=function(){ return first; }){ var
闭包的一件事
。
在下面的两段代码中,我将函数表达式作为回调传递
(在第一段代码中)当调用函数表达式时,我希望看到匿名函数关闭def
,但是当我调用second()
而不是查看变量first
(其中first
是updatedValue
)的“闭包”时,在全局变量环境中搜索并查找first
,其中first的值为oldValue
function def(first="oldValue" , second=function(){
return first;
}){
var first="updatedValue";
console.log('inside',first);
console.log('function',second());
}
//OUTPUT:
inside updatedValue
function oldValue
另一方面,如果您没有在def中声明first
,它将second()
控制台日志updatedValue
function def(first="oldValue" , second=function(){
return first;
}){
first="updatedValue"; // NOTE: removed the `var` here
console.log('inside',first);
console.log('function',second());
}
//OUTPUT:
inside updatedValue
function updatedValue
有人能解释一下这里发生了什么吗?如ES规范所述,使用默认参数创建默认参数所在的新范围,然后为以下参数和函数体创建另一个范围。这意味着
first
引用封闭默认参数范围内的变量,而var first
在函数范围内对其进行阴影处理
您的代码基本上与以下代码相同:
function def(_first, _second) {
// Scope of the first default parameter
var first = _first || "default";
(function() {
// Scope of the second default parameter
var second = _second || function(){
return first;
};
(function() {
// The functions scope
var first = "updatedValue"; // scoped here
console.log('inside',first);
console.log('function',second());
})();
})();
}
您没有将闭包作为参数传递。您正在为参数定义一个默认初始化器,该参数在未传递任何内容时使用。