简体   繁体   中英

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." 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. 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. 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() {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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