简体   繁体   English

如何将参数传递给 JavaScript 函数中的匿名函数?

[英]How do I pass arguments to an anonymous function within a function in JavaScript?

Let's consider following example让我们考虑以下示例

function apple(fn) {
    fn();
}

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

Arguments are passed to a function when it is called .参数在调用传递给函数。 So you can't per se.所以你本身不能。 You have to pass them when you call it:调用时必须传递它们:

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

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

If you want to define the value when you define the function, then just put it in the function:如果你想在定义函数的时候定义值,那么只要把它放在函数中:

function apple(fn) {
    fn();
}

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

A more complex solution would be to create a function which calls the anonymous function with arguments and then pass the new function… but that is just pointless complexity for the example you provide.更复杂的解决方案是创建一个函数,该函数使用参数调用匿名函数,然后传递新函数……但这对于您提供的示例来说只是毫无意义的复杂性。

function apple(fn) {
    fn();
}

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

Your code calls the anonymous function with no arguments:您的代码调用不带参数的匿名函数:

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

You can pass something to it from apple :你可以从apple传递一些东西给它:

function apple(fn) {
    fn(0);
}

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

Or, you can let apple pass arguments for your anonymous function:或者,您可以让apple为您的匿名函数传递参数:

function apple(fn,...args) {
    fn(...args);
}

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

Alternatively, you can bind your anonymous function, to prefix it with arguments:或者,你可以绑定你的匿名函数,用参数作为前缀:

function apple(fn) {
    fn();
}

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

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

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