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

我有这个:

addContact(entityId, refreshContactList());

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

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


当前回答

示例1:

funct("z", function (x) { return x; });

function funct(a, foo){
    foo(a) // this will return a
}

示例2:

function foodemo(value){
    return 'hello '+value;
}

function funct(a, foo){
    alert(foo(a));
}

//call funct    
funct('world!',foodemo); //=> 'hello world!'

看看这个

其他回答

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

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

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

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

示例1:

funct("z", function (x) { return x; });

function funct(a, foo){
    foo(a) // this will return a
}

示例2:

function foodemo(value){
    return 'hello '+value;
}

function funct(a, foo){
    alert(foo(a));
}

//call funct    
funct('world!',foodemo); //=> 'hello world!'

看看这个

要将函数作为参数传递,只需删除括号!

function ToBeCalled(){
  alert("I was called");
}

function iNeedParameter( paramFunc) {
   //it is a good idea to check if the parameter is actually not null
   //and that it is a function
   if (paramFunc && (typeof paramFunc == "function")) {
      paramFunc();   
   }
}

//this calls iNeedParameter and sends the other function to it
iNeedParameter(ToBeCalled); 

这背后的想法是函数与变量非常相似。而不是写作

function ToBeCalled() { /* something */ }

你不妨写

var ToBeCalledVariable = function () { /* something */ }

两者之间有细微的差别,但无论如何,它们都是定义函数的有效方法。现在,如果您定义了一个函数并将其显式分配给一个变量,那么您可以将其作为参数传递给另一个函数,这看起来非常合乎逻辑,而且不需要括号:

anotherFunction(ToBeCalledVariable);

通过使用ES6:


const invoke = (callback) => {
  callback()
}


invoke(()=>{
  console.log("Hello World");
})

有时,当您需要处理事件处理程序,因此需要将事件作为参数传递时,大多数现代库(如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);
}