javascript 将参数传递给 IIFE

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18552553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:22:33  来源:igfitidea点击:

Passing arguments to an IIFE

javascript

提问by Johan

What's the correct syntax for passing arguments to an IIFE stored in a variable?

将参数传递给存储在变量中的 IIFE 的正确语法是什么?

Example below tells me that foois not defined, regardless on if I call the function or not:

下面的示例告诉我foo未定义,无论我是否调用该函数:

var bar = (function(foo){

    return { 
        getFoo: function(){
            return foo;
        } 
    }

})(foo);

console.log(bar.getFoo(1));

http://jsfiddle.net/eSTkL/

http://jsfiddle.net/eSTkL/

回答by bfavaretto

The IIFE is immediatelyinvoked. You are passing footo it at the moment of invocation, and I suppose it's undefined.

立即调用IIFE 。你foo在调用的时候传递给它,我想它是未定义的。

What gets stored in baris not the IIFE, but the object returned by the IIFE, that doesn't have anything to do with foo (beside having access to it via closure). If you want foo to be 1, don't pass that value to getFoo, but to the IIFE itself:

存储的bar不是 IIFE,而是 IIFE 返回的对象,这与 foo 没有任何关系(除了可以通过闭包访问它)。如果您希望 foo 成为1,请不要将该值传递给getFoo,而是传递给 IIFE 本身:

var bar = (function(foo){

    return { 
        getFoo: function(){
            return foo;
        } 
    }

})(1);

console.log(bar.getFoo()); // 1

If you want a getter and a setter (actually, getter/setter-like functions), use this:

如果你想要一个 getter 和一个 setter(实际上是类似 getter/setter 的函数),使用这个:

var bar = (function(foo){

    return { 
        getFoo: function(){
            return foo;
        },
        setFoo: function(val) {
            foo = val;
        }
    }

})(1);

console.log(bar.getFoo()); // 1
bar.setFoo(2);
console.log(bar.getFoo()); // 2

回答by user2736012

The foothat you're passing to the IIFE isn't defined. You should define fooin the outer variable environment first.

foo您传递到IIFE没有定义。您应该foo首先在外部变量环境中定义。

var foo = "foobar";

var bar = (function(foo){

    return { 
        getFoo: function(){
            return foo;
        } 
    }

})(foo);


Or just define it directly in the argument position.

或者直接在参数位置定义它。

var bar = (function(foo){

    return { 
        getFoo: function(){
            return foo;
        } 
    }

})("foobar");


Also note that you're passing a value to getFoo(), but you're not actually using it in the method.

另请注意,您将值传递给getFoo(),但实际上并未在方法中使用它。

//         v----never gets used
bar.getFoo(1)

回答by Soupedenuit

Why not simply:

为什么不简单:

var bar = (function(){

  return { 
    getFoo: function(foo){
        return foo;
    } 
  }

})();

console.log(bar.getFoo(1));

Works for me.

对我来说有效。

回答by Daniel A. White

It is the foothat you are passing into the function.

这是foo你传递给函数的。