本文介绍了Javascript语法:立即调用带参数的函数表达式(IIFE)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直看到这样的代码:

I have always seen code like this:

(function(){
   //code here
})();

此代码如何运作?哪个函数接收哪些参数?

How does this code work? Which function receives which parameters?

(function(factory){
   //code here
}(function($){
  //other code here
}));


推荐答案

function($){
  //other code here
}

此块已通过作为外部IIFE的参数。写这样可能更清楚:

This block is passed as a parameter to the outer IIFE. It might be clearer to write it like this:

var factoryDef = function($) { ... };

(function(factory) {
    // this is the outer IIFE
    var someVar = {};
    // you can call:
    factory(someVar);
    // the previous line calls factoryDef with param someVar
}(factoryDef));

所以 factory(someVar)是一样的as factoryDe​​f({});后者只是 factory (函数 factoryDe​​f )的值,其值为 someVar {} 。)

So factory(someVar) is the same as factoryDef({}); the latter is simply the value of factory (which is the function factoryDef) called with the value of someVar (which is {}.)

这有意义吗?

这篇关于Javascript语法:立即调用带参数的函数表达式(IIFE)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 23:36