Why is the function called? JavaScript / Window

前端 未结 2 1247
暖寄归人
暖寄归人 2021-01-19 03:15

I have the following code in my HTML file:

    

        
相关标签:
2条回答
  • 2021-01-19 03:22

    The function expression is followed by parenthesis:

     window.never = function() { ... }
     (...)
    

    The line break after the function expression does not terminate the variable statement, so for the parser that's a function call:

    function() { ... }(...)
    

    In fact, you are using the very same technique here:

    (function(d, s, id){
      // ...
    }(document, 'script', 'streamrail-jssdk'))
    

    That's a function expression followed by (...) and it calls the function.

    Solution: Add a semicolon after the definition and you are good.


    If I change the never function to be off the global scope ... Then it is not being called.

    In that case the function definition is interpreted as function declaration, not expression. A function declaration is more like a statement and therefore cannot be part of a CallExpression. The following parenthesis are therefore interpreted as grouping operator (like you intended).

    0 讨论(0)
  • 2021-01-19 03:26

    Place the semi-colon after the function declaration:

        window.never = function() {
                 console.log('this function is never called');
        };
    

    It's because of the (...) directly afterwards that triggers the function call.

        window.never = function() {
                 console.log('this function is never called');
        }
        ( ... ) // <-- Triggers call of `window.never`
    
    0 讨论(0)
提交回复
热议问题