javascript 函数声明不应放在块中。使用函数表达式或将语句移到外部函数的顶部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14427077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:37:58  来源:igfitidea点击:

Function declarations should not be placed in blocks. Use a function expression or move the statement to the top of the outer function

javascriptjslintjshint

提问by Jamie Hutber

I have the following code:

我有以下代码:

if (typeof console === "object" && typeof console.error === "function") {
    function e(msg) {"use strict"; console.info(msg);}
}

For which jsLint gives the following error:

对于哪个 jsLint 给出以下错误:

Function statements should not be placed in blocks. Use a function expression or move the statement to the top of the outer function.

函数语句不应放在块中。使用函数表达式或将语句移到外部函数的顶部。

Why is it giving this error and what does it mean?

为什么会出现此错误,这是什么意思?

采纳答案by Tomas Kirda

You should not be creating function inside if block. You are much better off doing:

您不应该在 if 块中创建函数。你最好这样做:

var e = function(){};

if(typeof console === "object" && typeof console.error === "function"){
    e = function (msg){ ... };
}

回答by KyleMit

Explanation

解释

From the jsLintErrors page about the warning Function statements should not be placed in blocks:

从 jsLintErrors 页面中关于警告函数语句不应放置在块中

This error is raised to highlight code that may not work as you expect it to. In most environments Your code will run without error, but maybe not in the way you expect. In some environments it could cause a fatal syntax error.

That's because Functiondeclarations are hoisted to the top of the scopein which they appear.

Therefore, it is not possible to conditionallydeclare a function with a block statement.

引发此错误是为了突出显示可能无法按预期工作的代码。在大多数环境中,您的代码运行时不会出错,但可能不会以您期望的方式运行。在某些环境中,它可能会导致致命的语法错误

那是因为Function声明被提升到它们出现的范围的顶部

因此,不可能使用块语句有条件地声明函数。

Example

例子

Let's explore issues raised by this problem with a simple example:

让我们通过一个简单的例子来探讨这个问题引发的问题:

if (true) {
    function example() {
        console.log('hello');
    }
}

The best case scenariois that your code is confusing. In the above example, it looks like what you'd like to do is only declare access to the function ifthe condition is true. However, when the function is hoisted to the top of the scope, it will actually be interpreted like this:

最好的情况是您的代码令人困惑。在上面的例子中,它看起来像什么,你想要做的只是给函数声明的访问,如果条件为真。但是,当函数被提升到作用域的顶部时,它实际上会被这样解释:

function example() {
    console.log('hello');
}
if (true) {}

This is dangerous because it doesn't look like what you'd expect based on the original code. The conditional block is actually empty (and unnecessary), and everybody has access to the function, regardless of whether the condition evaluates to true or false.

这很危险,因为它看起来不像您基于原始代码所期望的那样。条件块实际上是空的(并且是不必要的),每个人都可以访问该函数,无论条件的计算结果为真还是假。

The worst case scenariois that the browser doesn't understand what to do with the nested function and throws a syntax error when trying to use it. This depends on the engine running JavaScript. It seems like Firefox is one such engine. If you run the following code in Firefox, it will throw an error when executing the following code:

最坏的情况是浏览器不知道如何处理嵌套函数并在尝试使用它时抛出语法错误。这取决于运行 JavaScript 的引擎。Firefox 似乎就是这样一种引擎。如果在 Firefox 中运行以下代码,在执行以下代码时会抛出错误:

if (true) {
    example();
    function example() {
        console.log('hello');
    }
}

If you open up your console, you should see the following error:

如果您打开控制台,您应该会看到以下错误:

ReferenceError: example is not defined

参考错误:示例未定义

Solution

解决方案

So how can you fix this?

那么你怎么能解决这个问题呢?

Use a function assignment instead of a function declaration

使用函数赋值代替函数声明

Here's a quick breakdown:

这是一个快速细分:

// Declaration
function declarationFunction() {}

// Assignment
var assignmentFunction = function() {}

Function Assignmentsare nothoisted to the top of the scope.
Function Declarationsare hoisted to the top of the scope.

功能分配没有提升到范围的顶部。
函数声明被提升到作用域的顶部。

So to conditionally set the example function, just assign it within the block like this:

因此,要有条件地设置示例函数,只需在块中分配它,如下所示:

var example;
if (true) {
    example = function() {
        console.log('hello');
    }
}