在条件内提升功能 [英] Hoisting of functions inside conditionals

查看:97
本文介绍了在条件内提升功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解如何在javascript中进行提升,函数在变量之前被提升,只有声明被提升。但当我遇到 if / else 条件时,如下所示:

I understanding how hoisting in javascript occurs, functions are hoisted before variables, and only the declarations are hoisted. But When I came across hoisting inside if/else conditionals, like this one:

foo(); // "b is the output"
var a = true;

if (a) {
  function foo() { console.log("a"); }
}
else {
  function foo() { console.log("b"); }
}

现在条件为真,所以根据if块, a 应该是输出,但由于某种提升,我假设 b 是输出。

Now the conditional is true, so according to the if block, a should have been the output, but due to some kind of hoisting I assume b is the output.

那么如何是 b 输出?

推荐答案

(忽略某些旧浏览器可能具有的略微狡猾的行为:)

(Ignoring the slightly dodgy behaviour that certain old browsers may have had:)

在Javascript中,函数语句的范围包含在包含函数中(如果没有包含函数,则为全局函数),它们不在if或else范围内。循环块。所以你不能以这种方式有条件地声明一个函数 (它可以用另一种方式完成;见下文)。如果在同一范围内声明多个具有相同名称的函数,则后一个函数将覆盖第一个函数。

In Javascript, function statements are scoped within the containing function (or globally if there is no containing function), they're not scoped within an if or else or loop block. So you can't declare a function conditionally in that manner (it can be done another way; see below). And if you declare more than one function with the same name in the same scope the later one will overwrite the first one.

所以你的代码会发生什么:

So what happens with your code is:


  1. 这两个功能声明被悬挂,但是

  1. Both function statements are hoisted, but

它们都具有相同的名称,因此第一个被第二个覆盖。

They both have the same name so the first is overwritten by the second.

已创建变量 a 但尚未分配值。

The variable, a is created but not yet assigned a value.

执行 foo()语句,记录b

a 被赋值 true

执行if。条件为真,但if和else分支实际上都没有做任何事情,因为它们不包含除了之前提升的函数声明之外的语句。

The if is executed. The condition is true, but neither the if nor else branches actually do anything because they don't contain statements other than the function declarations that were hoisted earlier.

如果要有条件地创建函数,则必须声明变量,然后为其分配函数表达式。然后你不能在该任务之后调用该函数:

If you want to create functions conditionally you have to declare a variable and then assign a function expression to it. And then you can not call the function until after that assignment:

var foo;
var a = true;

if(a)
    foo = function() { console.log("a"); };
else
    foo = function() { console.log("b"); };

foo();

这篇关于在条件内提升功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆