简体   繁体   中英

Closure in JavaScript with inline function

Lets say, I have defined a function like

var f = function(cb){cb()};

Now, if I pass a callback function it will work:

f(()=>{console.log("ccb")}); //print: ccb

But if I pass a argument, in this case x will be undefined:

f((x)=>{console.log("x:"+x);}); // x will be undefined

so one solution is to use closure,

function cba(x){
      return function(){
        console.log("ccbbaa:"+x)
      }
}

f(cba(20)); //will work give output: ccbbaa:20

But if I am trying to achieve closure using inplace function, considering xx is defined.

var xx = 20;
f(function(xx){
    return function(){
        console.log("xxx: "+xx)
    }
});

callback inside f is not even called. Why? How will we can use this inline function to make it work? I am studying closures so wanted to understand this. Any help is appreciated.

In your code you're not calling your inline function with xx . You're just passing the inline function to f which will be executed it but that will not print anything because the called inline function simply returns another function which is then never called.

 var f = function(cb){cb()}; var xx = 20; f((function(xx){ return function(){ console.log("xxx: "+xx) } })(xx));

Use bind to bind the parameter:

 const f = function(x){x()}; const param = 12 f(function(x){ console.log("ccbbaa:"+x) }.bind(null, param))

The only way to make this work is to give the anonymous function a default value for xx

f(function(xx=20){
    (function(){
        console.log("xxx: "+xx)
    })(xx);
});

inline function returns another function which is never called.

 var f = function(cb){cb()};
    var xx = 20;
    f((function(xx){
        return function(){
            console.log("xxx: "+xx)
        }
    })(xx));

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