委托javascript

时间:2009-10-09 14:19:49

标签: javascript-events

我有一个功能,我需要调用另一个函数,我们将动态jus,我知道函数名称。

像我的功能一样

myfunction(obj){
otherfunction(?);
}

其他功能可能

otherfunction(obj){
}

otherfunction(){
}

我不知道是否传递参数。

我该如何调用方法

5 个答案:

答案 0 :(得分:2)

你可以用任何参数来调用javascript函数:

function myFunction ( firstValue, secondValue )
{
  if ( firstValue ) alert ( firstValue );
  if ( secondValue ) alert ( secondValue );
}


myFunction (); //works but no alert
myFunction ("Hello");// 1 alert
myFunction ("Hello", "World");// 2 alerts

你看到所有三个方法调用都有效,尽管它是用2个参数声明的

答案 1 :(得分:1)

在JavaScript中没有任何方法可以获得函数签名。但是,您可以只传递您可能需要的任何参数,如果不需要它们,函数将忽略它们。它不会导致错误。

答案 2 :(得分:1)

JavaScript实际上并不要求您将所有参数传递给函数。或任何参数。或者,您可以传递比其签名中的函数名称更多的参数。

如果函数定义了一个参数obj,你只需将其称为

otherfunction();

然后obj就是未定义的。

答案 3 :(得分:1)

通过查看arguments局部变量,无论放入函数签名中的内容如何,​​都可以获取传递给函数的参数列表。

您可以使用函数apply方法调用具有任意数量参数的函数。

因此,要创建一个包装函数,将其所有参数传递给包装函数:

function myfunction() {
    otherfunction.apply(window, arguments);
}

这是你想要做的吗?

windowthis在包装函数中设置的值;如果没有特定对象,则调用方法,全局{{1}通常使用对象。)

答案 4 :(得分:0)

您可以将函数用作

function printOut(func,msg){
 return func(msg)
}

function test1(msg){
return "am test1 " + msg;

}

function test2(msg){
return "am test2 " +msg;
}


console.log(printOut(test2,"Function !!!"));