What does the exclamation mark do before the function?

后端 未结 9 1869
误落风尘
误落风尘 2020-11-21 04:47
!function () {}();
9条回答
  •  我在风中等你
    2020-11-21 05:10

    There is a good point for using ! for function invocation marked on airbnb JavaScript guide

    Generally idea for using this technique on separate files (aka modules) which later get concatenated. The caveat here is that files supposed to be concatenated by tools which put the new file at the new line (which is anyway common behavior for most of concat tools). In that case, using ! will help to avoid error in if previously concatenated module missed trailing semicolon, and yet that will give the flexibility to put them in any order with no worry.

    !function abc(){}();
    !function bca(){}();
    

    Will work the same as

    !function abc(){}();
    (function bca(){})();
    

    but saves one character and arbitrary looks better.

    And by the way any of +,-,~,void operators have the same effect, in terms of invoking the function, for sure if you have to use something to return from that function they would act differently.

    abcval = !function abc(){return true;}() // abcval equals false
    bcaval = +function bca(){return true;}() // bcaval equals 1
    zyxval = -function zyx(){return true;}() // zyxval equals -1
    xyzval = ~function xyz(){return true;}() // your guess?
    

    but if you using IIFE patterns for one file one module code separation and using concat tool for optimization (which makes one line one file job), then construction

    !function abc(/*no returns*/) {}()
    +function bca() {/*no returns*/}()
    

    Will do safe code execution, same as a very first code sample.

    This one will throw error cause JavaScript ASI will not be able to do its work.

    !function abc(/*no returns*/) {}()
    (function bca() {/*no returns*/})()
    

    One note regarding unary operators, they would do similar work, but only in case, they used not in the first module. So they are not so safe if you do not have total control over the concatenation order.

    This works:

    !function abc(/*no returns*/) {}()
    ^function bca() {/*no returns*/}()
    

    This not:

    ^function abc(/*no returns*/) {}()
    !function bca() {/*no returns*/}()
    

提交回复
热议问题