简体   繁体   English

“函数定义可能不会出现在语句中”的含义是什么

[英]What's the meaning of “Function definitions may not appear within statements”

What's the meaning of this "Function definitions may not appear within if statements, while loops, or any other statements." “函数定义可能不会出现在if语句,while循环或任何其他语句中”的含义是什么。 I'm quite confuse with this statement. 我对这句话很困惑。

One issue with what you're reading in the book is that a function definition (which is different than a function assignment) is essentially hoisted to the top of the host function in some browsers so putting it inside a statement (like inside an if statement) is downright misleading. 您在书中所读内容的一个问题是,在某些浏览器中,函数定义(与函数赋值不同)实际上被提升到宿主函数的顶部,因此将其放入语句中(例如,在if语句中) )是完全误导的。 The code will make it look like the function will only be defined if that branch of the if statement executes, but that will not necessarily be the case. 该代码使它看起来仅在if语句的该分支执行时才定义该函数,但不一定如此。 So, it's a bad practice. 因此,这是一个不好的做法。 It probably works in many cases, but is a bad practice. 它可能在许多情况下都有效,但这是一个坏习惯。

So, rather than this: 因此,而不是这样:

function main(foo) {
    if (foo) {
        function internal() {
            // code here
        }
        // code here
    }
}

Put the internal function up at the top; 将内部功能放在顶部;

function main(foo) {
    function internal() {
        // code here
    }
    if (foo) {
        // code here
    }
}

FYI, in strict mode internal function definitions are only allowed at the top. 仅供参考,在严格模式下,内部函数定义仅在顶部。 Condition function assignments can always be done with this syntax: 条件函数的分配始终可以使用以下语法完成:

var internal;
if (foo) {
    internal = function() {}
}

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

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