编写IIFE有哪些不同的方式?他们的用例是什么? [英] What are the different ways of writing an IIFE? What are their use cases?

查看:101
本文介绍了编写IIFE有哪些不同的方式?他们的用例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始阅读这本书。第2章说有不同的方法来编写一个IIFE:

$ $ $ $ $ $ c $!$ function $($)($)
〜 function(){}()
+ function(){}()
-function(){}()
new function(){}
1,function() {}()
1&& function(){}()
var i = function(){}()

作者说:


每种表现都有其独特的品质和优势 -


我是一个新手给JS。我知道什么是IIFE,但是这些IIFE形式究竟做了什么?

解决方案

为什么要这样?



,让我们从为什么要这么做?开始。



答案是:将函数中的所有变量和函数声明保留为private。通常这是为了避免全局性(避免全局性是一个好主意TM TM)。例如:

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

foo();

var answer = 42;
}();

感谢IIFE(在此上下文中称为范围函数), foo answer 不是全局变量。它们对函数中的代码是私有的,除非它们以某种方式导出。



即使不在全局范围内,您也可以这样做,只是为了避免污染任何范围'b。b

IIFE通常有其他用途,但您引用的风格通常用于范围界定。



举例



作者严重夸大了每个人都有自己独特的品质和优势的情况。

>

除非您使用返回值,否则这些都完全相同:

<$ p $ b $ function $(){$($)$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ }()
1,function(){}()
1&& function(){}()

它们中的代码在函数中运行,范围也是可以的。



我们也可以将这些代码添加到列表中:

 (function(){}())
(function(){})()
0 ||函数(){}()
1 ^ function(){}()//任何二进制数学运算符代替^也可以工作

当然,以上所有的 1 都不是特别的。其中大部分可以是任何数字(或几乎任何其他数字),但是使用&& 的那个不适用于 0 null undefined NaN false (该函数不会运行)。类似地,只要启动它的值为falsey,那么 0 || ... 就会工作。



在这一个中:

  var i = function(){}()

...唯一的区别是它声明了一个变量, i ,它存储返回值。当然,这可能是一个很大的区别。考虑这个更明显的版本:

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

return {/ * niftynamespacestuff here / /};
})();

最后:

  new function(){} 

创建一个新对象,然后调用函数将这个设置为新对象。如果你在函数中不使用这个,那完全没有意义。如果你这样做,那么它是否有用取决于你对这个做了什么。






注意:如果有任何代码可能无法控制即将发生在您的范围界定功能之前(例如,在合并和缩小文件时),最好开始全部 ; ,例如:

  ;!函数(){}()
;〜function(){}()
; + function(){}()
; -function(){}()
; 1,function(){}()
; 1&& function(){}()
;(function(){}())
;(function(){} )()
; 0 || function(){}()
; 1 ^ function(){}()//任何二进制数学运算符代替^也可以工作

其中一些技术上并不需要一个,但大多数都是。没有它们的副作用可能是微妙的,或灾难性的。考虑:

代码之前的代码:

  obj.prop = function(){
//做一些大而糟糕的事情
}

然后你的代码:

 (function(){}())

自动分号插入不会踢入!结果? obj.prop 函数被调用,我们的IIFE作为参数传递给它。这将使它更明显:

  obj.prop = function(){
//做一些大而糟糕的事情
}(function(){}())

c>()现在正在调用函数?

同样:

<$ p $










$ b

  + function(){}()

突然间, criticalValue 被搞乱了。为什么?因为:

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

Doh!



拥有多个; 连续无害,所以如果你从一开始就不会遇到麻烦。


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?

解决方案

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.

这篇关于编写IIFE有哪些不同的方式?他们的用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆