为什么命名的IIFE会导致ReferenceError之外? [英] Why does a named IIFE result in a ReferenceError outiside of it?

查看:41
本文介绍了为什么命名的IIFE会导致ReferenceError之外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我为以下代码得到" ReferenceError : Person 未定义" ?

Why did I get "ReferenceError: Person is not defined" for the following code?

(function Person() {
  console.log('Hi');
}());
console.log(Person);

由于运行了功能 Person ,因此将首先创建它.但是,我无法解释为什么不认识它.我唯一的想法是IIFE会忽略它们的名字.

Since function Person is run, it is first created. However, I cannot explain why it is not then recognized. My only thought is that IIFE ignores the name they are given.

推荐答案

您会收到此错误,因为由函数 expression 创建的函数的名称未添加到表达式所在的作用域中.(它是在函数体内的 范围,因此名称不会被忽略.)函数 declaration 会在其出现的范围内创建名称,但不会在名称范围内创建该名称.命名函数表达式.这就是定义JavaScript的方式.

You get the error because the name of a function created by a function expression is not added to the scope the expression is in. (It is in-scope within the function body, so the name isn't just ignored.) A function declaration creates the name in the scope where it appears, but not a named function expression. That's just how JavaScript is defined.

如果坚持使用表达式而不是函数声明很重要(例如,因为表达式是在代码的逐步处理中完成的,而声明是在更早的时候完成的),则可以使用变量:

If it's important that you stick to using an expression rather than a function declaration (for instance, because expressions are done in the step-by-step processing of the code, whereas declarations are done earlier), you can do it with a variable:

var Person = function Person() {
    console.log('Hi');
};
Person();
console.log(Person);

这对于ES6更为简洁,因为在ES6中,您可以命名函数而无需使用命名函数表达式:

And that gets more concise with ES6, because in ES6 you can name a function without using a named function expression:

var Person = function() {
    console.log('Hi');
};
Person();
console.log(Person);

在ES5中,该函数没有名称(除非许多JavaScript引擎给了它一个名字).在ES6中,该函数确实具有一个名称,该名称取自变量.

In ES5, that function wouldn't have a name (except many JavaScript engines gave it one anyway). In ES6, that function does have a name, which is taken from the variable.

语言设计师不一定需要为什么"做决定,例如不把名字放在范围内,但是当您想到做这样的事情时,这是有道理的:

Language designers don't necessarily need a "why" for decisions like not putting the name in scope, but it makes sense when you think of doing things like this:

// ES5 and earlier
var x = {
    foo: function foo() { /* ... */ },
    bar: function bar() { /* ... */ },
    baz: function baz() { /* ... */ }
};

上面的代码添加了 x 而不是 foo bar baz .

It probably makes sense that the above adds x to the scope, but not foo, bar, and baz.

这篇关于为什么命名的IIFE会导致ReferenceError之外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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