javascript - if 语句的函数作用域

标签 javascript scope execution-time anti-patterns

我正在尝试不寻常的Javascript“模式”,并且如果不希望在父作用域中声明变量,我想到了一种潜在的简洁的作用域 block 方法。

例如,而不是:

function someFunction () {
  var x, t;

  for (x = 0; x < 10000; x += 1) {
    if (true) {
      t = x;
    }
  }
}

可以使用以下方法保存额外的父变量:

function someFunction () {
    var x;

    for (x = 0; x < 10000; x += 1) {
      if (true) { void function () {
        var t = x;
      }(); }
    }
}

但是,我的 jsperf ( http://jsperf.com/scoped-if ) 显示,当重复使用时,可能会对性能产生负面影响。显然,这个结果表明上述不是一种实用的模式,除非谨慎执行。

据我了解,缓慢可能是由于重复创建和销毁执行上下文 (1 + 10000),而第一个只涉及 1。

我的问题是,考虑到上述条件(不在循环中使用),这种模式仍然有用吗?为什么上下文的创建成本如此之高?

最佳答案

是的,一个 IIFE是模仿 block scope 的合理方式.

更好的方法是使用let ,如有必要,使用 ES6 转译器:

function someFunction () {
    var x;

    for (x = 0; x < 10000; x += 1) { 
      if (true) { 
        let t = x;
        // Do something with t here
      }
      // because it is not defined here
    }
    // or here
}
// and even a var wouldn't be defined here

ES6 compatibility table for let

关于javascript - if 语句的函数作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28240429/

相关文章:

javascript - Node.js 和 socket.io,客户端不共享计数器

c# - 是否可以在不包括阻塞/抢占时间的情况下测量线​​程的执行时间?

java - 使用 getCurrentThread UserName() 获取执行时间

Javascript Cookie 脚本 Opera 浏览器

javascript - indexOf返回值条件

php - 如何在 PHP 中使大的多维变量看起来更短?

c++ - 在 C++ 中计算执行时间

javascript - 创建从右到左的屏幕外子菜单导航

javascript - jQuery 每个函数不使用数组的顺序

javascript - jQuery 插件选项