功能默认参数有些问题? [英] Some problems in function default parameters?
问题描述
看到这个
让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 functionbar
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屋!