功能默认参数有些问题? [英] Some problems in function default parameters?

查看:72
本文介绍了功能默认参数有些问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到这个

 让foo ='outer'; 

函数栏(func = x => foo){
let foo ='inner';
console.log(func());
}

bar(); // outer

我想知道为什么输出是'外部'而不是'内部'。我知道JavaScript有词法范围。这个输出让我觉得功能 x => foo 定义为函数 bar

解决方案

< blockquote>

我知道js有词法范围,这个输出让我觉得功能 x => foo 定义为函数 bar


不完全是。它位于:参数声明中,它有自己的作用域,可以访问其他参数但不能访问正文。默认初始化程序基本上可以免费使用

  let foo ='outer'; 
函数栏(){
var func = arguments [0] === undefined? x => foo:arguments [0];
{
let foo ='inner';
console.log(func());
}
}
bar(); //外部


See this

let foo = 'outer';

function bar(func = x => foo) {
  let foo = 'inner';
  console.log(func()); 
}

bar(); //outer

I want to know why the output is 'outer' rather than 'inner'. I know JavaScript has lexical scope. This output makes me feels like that the function x => foo is defined out of function bar

解决方案

I know js has lexical scope, This output makes me feels like that the function x => foo is defined out of function bar

Not exactly. It's in-betweeen: in the parameter declaration, which has its own scope with access to the other parameters but not the body. The default initialiser basically desugars to

let foo = 'outer';
function bar() {
  var func = arguments[0] === undefined ? x => foo : arguments[0];
  {
    let foo = 'inner';
    console.log(func());
  }
}
bar(); // outer

这篇关于功能默认参数有些问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆