简体   繁体   中英

How can I pass a variable into a IIFE?

I want to use a closure in myObj so I can increment myIndex without having to add myIndex to the global namespace (aka, in TaskHandler ).

That works. But I also need to pass in myValue to the closure. I thought passing it through (function (param) { })(myValue); was the way to do it. But it's undefined.

TaskHandler.myFunction(value);

TaskHandler = {

     myFunction : function (value) {
         this.myObj.run(value);
     },

    myObj : {

        run : function (value) {
            this.doIt(value);
        },

        doIt : (function (value) {
            var myIndex = 0;
             return function () {
                myIndex++;
                 doSomethingWithValue(myIndex, value); //value undefined
             }
        })(value)

    },

};

The function your IIFE returns should accept the value argument, not the IIFE itself:

    doIt : (function () {
        var myIndex = 0;
         return function (value) {
            myIndex++;
             doSomethingWithValue(myIndex, value);
         }
    })()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM