简体   繁体   English

使用内联函数在 JavaScript 中关闭

[英]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:但是如果我传递一个参数,在这种情况下 x 将是未定义的:

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.但是,如果我尝试使用 inplace 函数实现闭包,则考虑 xx 已定义。

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

callback inside f is not even called.甚至没有调用 f 内部的回调。 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 .在您的代码中,您没有使用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.您只是将内联函数传递给f ,它将被执行,但不会打印任何内容,因为被调用的内联函数只是返回另一个从未被调用的函数。

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

Use bind to bind the parameter:使用bind绑定参数:

 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使这项工作的唯一方法是为匿名函数提供 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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