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

我有这个:

addContact(entityId, refreshContactList());

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

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


当前回答

我用那个问题把头发都剪掉了。我无法让上面的例子发挥作用,所以我最后说:

function foo(blabla){
    var func = new Function(blabla);
    func();
}
// to call it, I just pass the js function I wanted as a string in the new one...
foo("alert('test')");

这就像一种魅力。。。至少我需要什么。希望这对一些人有所帮助。

其他回答

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

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);

您也可以使用JSON来存储和发送JS函数。

检查以下各项:

var myJSON = 
{
    "myFunc1" : function (){
        alert("a");
    }, 
    "myFunc2" : function (functionParameter){
        functionParameter();
    }
}



function main(){
    myJSON.myFunc2(myJSON.myFunc1);
}

这将打印“a”。

以下内容与上述内容具有相同的效果:

var myFunc1 = function (){
    alert('a');
}

var myFunc2 = function (functionParameter){
    functionParameter();
}

function main(){
    myFunc2(myFunc1);
}

这也具有以下相同的效果:

function myFunc1(){
    alert('a');
}


function myFunc2 (functionParameter){
    functionParameter();
}

function main(){
    myFunc2(myFunc1);
}

以及使用Class作为对象原型的对象范例:

function Class(){
    this.myFunc1 =  function(msg){
        alert(msg);
    }

    this.myFunc2 = function(callBackParameter){
        callBackParameter('message');
    }
}


function main(){    
    var myClass = new Class();  
    myClass.myFunc2(myClass.myFunc1);
}

您只需删除括号:

addContact(entityId, refreshContactList);

然后传递函数而不首先执行它。

下面是一个示例:

函数addContact(id,refreshCallback){refreshCallback();//如果需要,也可以传递参数//refreshCallback(id);}函数refreshContactList(){alert(“Hello World”);}addContact(1,refreshContactList);

通过使用ES6:


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


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

我建议将参数放在一个数组中,然后使用.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