【问题标题】:How do I pass arguments to an anonymous function within a function in JavaScript?如何将参数传递给 JavaScript 函数中的匿名函数?
【发布时间】:2019-12-15 07:42:15
【问题描述】:

让我们考虑下面的例子

function apple(fn) {
    fn();
}

apple(function(a) { // Here how do I pass an integer value for a ?
    console.log(a);
});

【问题讨论】:

  • 当您拨打fn时,您可以传入一个号码:fn(1);

标签: javascript function parameter-passing anonymous-function


【解决方案1】:

参数在被调用时传递给函数。所以你本身不能。调用时必须通过它们:

function apple(fn) {
    fn("Here you can pass an argument");
}

apple(function(a) {
    console.log(a);
});

如果你想在定义函数的时候定义值,那么就放在函数里面:

function apple(fn) {
    fn();
}

apple(function() {
    console.log("Here you can hard code a value instead of using an argument");
});

更复杂的解决方案是创建一个函数,该函数使用参数调用匿名函数,然后传递新函数……但这对于您提供的示例来说只是毫无意义的复杂性。

function apple(fn) {
    fn();
}

apple(function(a) {
    console.log(a);
}.bind(null, "Here you can pass an argument"));

【讨论】:

    【解决方案2】:

    您的代码不带参数调用匿名函数:

    function apple(fn) {
        fn(); //Here
    }
    

    你可以从apple传递一些东西给它:

    function apple(fn) {
        fn(0);
    }
    
    apple(function(a) {
        console.log(a); //0
    });
    

    或者,您可以让apple 为您的匿名函数传递参数:

    function apple(fn,...args) {
        fn(...args);
    }
    
    apple(function(a) {
        console.log(a); //0
    }, 0);
    

    或者,您可以绑定匿名函数,为其添加参数前缀:

    function apple(fn) {
        fn();
    }
    
    apple((function(a) {
        console.log(a); //0
    }).bind(undefined, 0));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 1970-01-01
      • 2015-05-09
      相关资源
      最近更新 更多