传递JavaScript函数作为参数如何将函数作为参数传递,而不需要在“父”函数中执行或使用eval()?(因为我读到它是不安全的。)我有这个:addContact(entityId, refreshContactList());很管用,但问题是refreshContactList当函数被调用时触发,而不是在函数中使用时触发。我可以用eval()但根据我所读到的,这不是最好的做法。如何在JavaScript中将函数作为参数传递?
3 回答
潇湘沐
TA贡献1816条经验 获得超6个赞
addContact(entityId, refreshContactList);
function addContact(id, refreshCallback) { refreshCallback(); // You can also pass arguments if you need to // refreshCallback(id);}function refreshContactList() { alert('Hello World');}addContact(1, refreshContactList);
陪伴而非守候
TA贡献1757条经验 获得超8个赞
function foo(x) { alert(x);}function bar(func) { func("Hello World!");}//alerts "Hello World!"bar(foo);
function foo(x) { alert(x);}function bar(func) { func();}//alerts "Hello World!" (from within bar AFTER being passed)bar(function(){ foo("Hello World!") });
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"]);
添加回答
举报
0/150
提交
取消