javascript - ES5 中的 block 作用域

标签 javascript scope ecmascript-5 iife

我的作业遇到问题。这是作业:

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/

相关文章:

javascript - 带或不带国家代码的手机号码的正则表达式

javascript - 可折叠 TreeMap v4 和 Internet Explorer

JavaScript prototype.init 疯狂

javascript - 了解常见的 jQuery 插件样板

javascript - 在给定函数范围内使用变量而不传递

javascript - 为什么 Babel 需要 polyfill 而不是默认转译某些方法?

javascript - 使用 JSOM 在 SharePoint 列表功能区按钮中添加按钮

javascript - ES6 对象简写表示法可以与常规对象表示法结合使用吗?

android - Dagger 2 瞄准镜说明

javascript - 在Javascript中,如何显示setter/getter的函数体?