简体   繁体   English

在JavaScript中同时声明变量和函数

[英]Simultaneously Declaring Variables and Functions in JavaScript

Can anyone explain why 谁能解释为什么

function x() {
  console.log("Hello!");
}
var a = x;
a();
x();

produces 产生

Hello! 你好!
Hello! 你好!

but this 但是这个

var a = function x() {
  console.log("Hello!");
}
a();
x();

throws an error when you try to call function x? 尝试调用函数x时引发错误? Is the second x function not considered a hoisted function? 第二个x函数不被视为提升函数吗? I tried this in both nodejs and a browser. 我在nodejs和浏览器中都尝试过。

What you have in the second example is what's called a named function expression . 你在第二个例子中所拥有的是所谓的命名函数表达式

Its name is not added to the containing scope, but is accessible within the scope of the function itself: 它的名称不会添加到包含范围,但可以在函数本身的范围内访问:

var a = function x() {
  alert(x);
};
a();

This is useful in writing recursive functions or functions that otherwise reference themselves, as it ensures that the name won't get clobbered due to anything that happens outside the function's scope. 这在编写以其他方式引用自身的递归函数或函数时非常有用,因为它确保名称不会因函数范围之外发生的任何事情而被破坏。

It also allows you to create self-referencing functions in places where you can't use a function declaration, such as in an object literal: 它还允许您在无法使用函数声明的位置创建自引用函数,例如在对象文字中:

var myFavoriteFunctions = {
    factorial: function f(n) {
        return n === 1 ? 1 : n * f(n);
    },
    identity: function (v) { return v; }
};

console.log(myFavoriteFunctions.factorial(10));

Your first example is a function statement, which declares a name in its containing scope. 您的第一个示例是一个函数语句,它在其包含范围内声明了一个名称。

Your second example is a named function expression, which does not. 您的第二个示例是命名函数表达式,但不是。

For more information, see here . 有关更多信息,请参阅此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM