本文介绍了将论据传递给IIFE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

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

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

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

var bar = (function(foo){

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

})(foo);

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

推荐答案

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

The IIFE is immediately invoked. You are passing foo to it at the moment of invocation, and I suppose it's undefined.

存储在栏中的内容不是IIFE,而是IIFE返回的对象,不是与foo有关(除了通过关闭访问它)。如果你想要foo 1 ,请不要将该值传递给 getFoo ,而是传递给IIFE本身:

What gets stored in bar is 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:

var bar = (function(foo){

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

})(1);

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

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

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

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

这篇关于将论据传递给IIFE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 07:35