Why is the function called? JavaScript / Window

前端 未结 2 1258
暖寄归人
暖寄归人 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).

提交回复
热议问题