如何在函数不在“父”函数中执行或使用eval()的情况下将函数作为参数传递?(因为我读到这是不安全的。)

我有这个:

addContact(entityId, refreshContactList());

它可以工作,但问题是refreshContactList在调用函数时触发,而不是在函数中使用时触发。

我可以使用eval()绕过它,但根据我所读的,这不是最佳实践。如何在JavaScript中传递函数作为参数?


当前回答

JavaScript程序员中有一句话:“Eval是邪恶的”,所以要不惜一切代价避免它!

除了史蒂夫·芬顿的答案,你还可以直接传递函数。

function addContact(entity, refreshFn) {
    refreshFn();
}

function callAddContact() {
    addContact("entity", function() { DoThis(); });
}

其他回答

您也可以使用eval()执行相同的操作。

//A function to call
function needToBeCalled(p1, p2)
{
    alert(p1+"="+p2);
}

//A function where needToBeCalled passed as an argument with necessary params
//Here params is comma separated string
function callAnotherFunction(aFunction, params)
{
    eval(aFunction + "("+params+")");
}

//A function Call
callAnotherFunction("needToBeCalled", "10,20");

就是这样。我也在寻找这个解决方案,并尝试了其他答案中提供的解决方案,但最终从上面的例子中得到了效果。

我建议将参数放在一个数组中,然后使用.apply()函数将它们拆分。所以现在我们可以很容易地传递一个带有大量参数的函数,并以简单的方式执行它。

function addContact(parameters, refreshCallback) {
    refreshCallback.apply(this, parameters);
}

function refreshContactList(int, int, string) {
    alert(int + int);
    console.log(string);
}

addContact([1,2,"str"], refreshContactList); //parameters should be putted in an array

如果您可以将整个函数作为字符串传递,这段代码可能会对您有所帮助。

convertToFunc(“运行此('Micheal')”)函数convertToFunc(str){新函数(str)()} 函数runThis(名称){console.log(“Hello”,name)//打印Hello Micheal}

有时,当您需要处理事件处理程序,因此需要将事件作为参数传递时,大多数现代库(如react、angular)可能都需要这样做。

我需要重写OnSubmit函数(来自第三方库的函数),并对reactjs进行一些自定义验证,我传递了函数和事件,如下所示

原来

    <button className="img-submit" type="button"  onClick=
 {onSubmit}>Upload Image</button>

进行了一个新的函数上传,并将传递的Submit和事件作为参数调用

<button className="img-submit" type="button"  onClick={this.upload.bind(this,event,onSubmit)}>Upload Image</button>

upload(event,fn){
  //custom codes are done here
  fn(event);
}

事实上,看起来有点复杂,其实不然。

get方法作为参数:

 function JS_method(_callBack) { 

           _callBack("called");  

        }

您可以给出以下参数方法:

    JS_method(function (d) {
           //Finally this will work.
           alert(d)
    });