我的作业遇到问题。这是作业:
Given following function.
let rechne = function(x,y,operation) {
let ergebnis = x - y;
if (!operation) {
let ergebnis = x + y;
console.log(ergebnis);
}
return ergebnis;
}
Rewrite the function so that the desired block scope of the variables can be achieved in ES5.
所以我写了这个:
let rechneScope = function(x,y,operation) {
(function(){
let ergebnis = x - y;
})()
if (!operation) {
(function(){
let ergebnis = x + y;
console.log(ergebnis);
})()
}
return ergebnis;
}
假设我在 console.log 中调用了该函数,如 console.log(rechneScope(10, 2))
我预计第一个变量为 8,第二个变量为 12。
但是当我重新加载浏览器时,控制台总是为第二个变量打印 12,而对于第一个变量,结果不同。有时2个,有时8个,有时15个。我真的很困惑。为什么会发生这种情况?
最佳答案
首先,您假设所需的输出是 8
,那么 12
是错误的。第一个执行的 console.log
是包含 ergebnis = x + y
的日志,因此您应该看到 12
然后是 8
.
接下来,ES6 中引入了 let
,因此如果您将自己限制在 ES5 中,则只能使用 var
。
最后,确保将每个变量的整个范围包装在 IIFE 中。您在第一个函数之外return ergebnis
,以便该变量在该行代码执行时不再处于作用域内。
正确的实现是这样的:
var rechneScope = function(x, y, operation) {
return (function() {
var ergebnis = x - y;
if (!operation) {
(function() {
var ergebnis = x + y;
console.log(ergebnis);
})()
}
return ergebnis;
})()
}
console.log(rechneScope(10, 2))
我知道这不是你作业的一部分,但仅供引用,Babel不费心去尝试模拟 ES6 范围。以下是 Babel 编译相同内容的方式:
"use strict";
var rechne = function rechne(x, y, operation) {
var ergebnis = x - y;
if (!operation) {
var _ergebnis = x + y;
console.log(_ergebnis);
}
return ergebnis;
};
关于javascript - ES5 中的 block 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56227479/