Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 闭包在作为参数传递的函数表达式中是如何工作的?_Javascript_Closures - Fatal编程技术网

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());
     })();
   })();
 }
您没有将闭包作为参数传递。您正在为参数定义一个默认初始化器,该参数在未传递任何内容时使用。