Roy*_*mir 10 javascript ecmascript-6
看看这个使用Lazy Expressions的简单代码:
var x = 1;
function foo(x = 2, f = () => x) {
var x = 5;
console.log(f())
}
foo()Run Code Online (Sandbox Code Playgroud)
这里的输出是2.
我必须说我认为它应该输出5.但是 - 如果f关闭参数列表范围 - 如果它有一个范围,这将是合乎逻辑的.
因为看这个其他的例子(有点相关):
var x = 5;
var f = function() {
return x;
}
x = 1
f();
console.log(x)Run Code Online (Sandbox Code Playgroud)
这将输出1.(这是预期的结果.).
题
参数列表范围实际上是什么?这里有什么范围吗?(在参数列表中)
我没有在文档中找到与范围相关的信息.
函数参数有范围.
在第一个示例中,您分配了一个新x变量,这就是它不会覆盖的原因:
//Global x
var x = 1;
function foo(x = 2 /* Local scope x */ , f = () => x /* Local scope x bound to new function scope */ ) {
/* new local scope x. If you removed the "var", this would overwrite localscope x */
var x = 5;
/* All 3 x's accessed */
console.log(f(), x, window.x)
}
foo()Run Code Online (Sandbox Code Playgroud)
var x = 1;
function foo(x = 2, f = () => x) {
x = 5;
console.log(f(), x, window.x)
}
foo()Run Code Online (Sandbox Code Playgroud)
编辑1 - TypeScript
作为评论的答案.TypeScript编译此ES6版本:
//Global x
var x = 1;
function foo(x = 2 /* Local scope x */ , f = () => x /* Local scope x bound to new function scope */ ) {
/* new local scope x. If you removed the "var", this would overwrite localscope x */
var x = 5;
/* All 3 x's accessed */
console.log(f(), x, window.x)
}
foo()Run Code Online (Sandbox Code Playgroud)
进入:
//Global x
var x = 1;
function foo(x /* Local scope x */, f /* Local scope x bound to new function scope */) {
if (x === void 0) { x = 2; } /* Local scope x */
if (f === void 0) { f = function () { return x; }; } /* Local scope x bound to new function scope */
/* new local scope x. If you removed the "var", this would overwrite localscope x */
var x = 5;
/* All 3 x's accessed */
console.log(f(), x, window.x);
}
foo();Run Code Online (Sandbox Code Playgroud)
这样做是因为较旧的浏览器不支持参数声明,但与直接ES6版本相比,它与范围混淆.
| 归档时间: |
|
| 查看次数: |
240 次 |
| 最近记录: |