Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - What are the different ways of writing an IIFE? What are their use cases?

I have started reading this book. Chapter 2 says that there are different ways to write an IIFE:

!function (){}() 
~function (){}() 
+function (){}() 
-function (){}()
new function (){} 
1,function (){}() 
1&&function (){}() 
var i=function (){}()

The author says:

Each manifestation has its own unique qualities and advantages—some with fewer bytes, some safer for concatenation, each valid and each executable.

I'm a newbie to JS. I know what an IIFE is, but what do these IIFE forms do exactly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why do this?

Before we get to the list, let's start with "Why do this at all?"

The answer is: To keep any variables and function declarations within the function private. Commonly this is to avoid globals (avoiding globals is a Good IdeaTM). E.g.:

+function() {
    function foo() {
        /* ... */
    }

    foo();

    var answer = 42;
}();

Thanks to the IIFE (called a scoping function in this context), foo and answer are not globals. They're private to the code within the function, unless they get exported somehow.

You might do this even if not at global scope, just to avoid polluting whatever scope you're in.

IIFEs in general have other uses, but the style you've quoted is typically used for scoping.

The examples

The author is dramatically overstating the case that "each has its own unique qualities and advantages".

Unless you're using the return value, these are all exactly the same:

!function (){}() 
~function (){}() 
+function (){}() 
-function (){}()
1,function (){}() 
1&&function (){}() 

The code within them is run, scoped within the function.

We can add these to that list as well:

(function(){}())
(function(){})()
0||function (){}() 
1^function(){}() // any binary math operator in place of ^ also works

Of course, the 1 in all of the above is not special. Could be any number (or just about anything else) for most of them, but the one using && wouldn't work with 0, "", null, undefined, NaN, or false (the function wouldn't get run). Similarly, the one with 0||... works as long as the value starting it is falsey.

In this one:

var i=function (){}()

...the only difference is that it declares a variable, i, which stores the return value. That can, of course, be a big difference. Consider this more obvious version of it:

var MyPseudoNamespace = function() {
    // ...

    return { /* nifty "namespace" stuff here */ };
})();

Finally:

new function (){} 

That creates a new object and then calls the function with this set to the new object. If you don't use this within the function, it's utterly pointless. If you do, well, whether it's useful depends on what you do with this.


Note: If there's any possibility of code you don't control coming immediately before your scoping function (when you're combining and minifying files, for instance), it's best to start all of these off with a ;, e.g.:

;!function (){}() 
;~function (){}() 
;+function (){}() 
;-function (){}()
;1,function (){}() 
;1&&function (){}() 
;(function(){}())
;(function(){})()
;0||function (){}() 
;1^function(){}() // any binary math operator in place of ^ also works

Several of them don't technically need one, but most of them do. The side-effects of not having them can be subtle, or catastrophic. Consider:

Code before your code:

obj.prop = function() {
    // Do something big and awful
}

Then your code:

(function(){}())

Automatic Semicolon Insertion will not kick in! The result? the obj.prop function gets called, with our IIFE passed into it as an argument. This will make it more obvious:

obj.prop = function() {
    // Do something big and awful
}(function(){}())

See how those () are now invoking the function?

Similarly:

obj.criticalValue = 42

then

+function(){}()

Suddenly, criticalValue is messed up. Why? Because:

obj.criticalValue = 42+function(){}()

Doh!

Having multiple ; in a row is harmless, so if you start off with one, you're less likely to run into trouble.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...