Javascript,参数的参数:以函数名作为参数,怎么穿参数给这个函数?

第一个方法:匿名函数

function foo(x) {
   alert(x);
}
function bar(func) {
   func();
}

//alerts "Hello World!" (from within bar AFTER being passed)
bar(function(){ foo("Hello World!") });

第二个方式:使用 apply

function eat(food1, food2)
{
    alert("I like to eat " + food1 + " and " + food2 );
}
function myFunc(callback, args)
{
    //do stuff
    //...
    //execute callback when finished
    callback.apply(this, args);
}

//alerts "I like to eat pickles and peanut butter"
myFunc(eat, ["pickles", "peanut butter"]); 

https://stackoverflow.com/a/24091927/3054511

发布了188 篇原创文章 · 获赞 88 · 访问量 58万+

猜你喜欢

转载自blog.csdn.net/henryhu712/article/details/103237627
今日推荐