定义为函数调用参数的函数名称不会被提升。为什么不? [英] Function names defined as parameters to a function call aren't hoisted. Why not?

查看:118
本文介绍了定义为函数调用参数的函数名称不会被提升。为什么不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码。

<!DOCTYPE html>
<script>
  console.log(a);
  function a() {}
</script>

请注意, a 似乎在它之前被访问过被定义为。控制台输出为:( jsfiddle

Notice that a is seemingly accessed before it is defined. The console output is: (jsfiddle)

function a() {}

函数和变量名在之前定义任何其他代码运行,所以console.log调用在这里工作。这称为悬挂

Function and variable names are defined before any other code runs, so the console.log call works here. This is called hoisting.

但是如果函数被定义为函数调用中的参数,则不起作用。看看这段代码。

But this doesn't work if the function is defined as a parameters in a function call. Look at this code.

<!DOCTYPE html>
<script>
  function a() {}
  a(function b() {});
  console.log(b);
</script>

请注意,函数 b 是在里面定义的调用 a 。不在闭包内,而是在通话中。控制台输出为:( jsfiddle

Notice that the function b is defined inside of a call to a. Not inside of a closure, but inside of a call. The console output is: (jsfiddle)

Uncaught ReferenceError: b is not defined

我想知道为什么会这样发生。这是预期的行为吗?这种情况在Chrome和Firefox中都会发生。

I'm wondering why this happens. Is this the intended behavior? This happens in both Chrome and Firefox.

更新: jsfiddle 表明函数表达式中的名称在定义它们的作用域中永远不可用。但是,名称是在函数本身的范围内定义的。这意味着命名函数表达式可以引用名称,但仅限于函数内部。该名称也存储在函数的 name 参数中。

UPDATE: This jsfiddle shows that names in function expressions are never available in the scope in which they are defined. However, the name is defined inside the scope of the function itself. This means a named function expression can refer to the name, but only inside the function. The name is also stored in the function's name parameter.

<!DOCTYPE html>
<script>
  console.log(a); // undefined
  var a = function b() {
    console.log(b); // function b() { … };
  };
  a(); // function b() { … };
  console.log(a); // function b() { … };
  console.log(a.name); // b
  console.log(b); // Uncaught ReferenceError: b is not defined
</script>


推荐答案

内部 a(功能b (){}); ,该函数是函数表达式而不是函数声明(只有被挂起的函数)。您可以查看 var functionName = function(){} vs function functionName(){} 的差异。

Inside a(function b() {});, the function is a function expression and not a function declaration (only which are hoisted). You might have a look at var functionName = function() {} vs function functionName() {} for the difference.

这篇关于定义为函数调用参数的函数名称不会被提升。为什么不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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