Delegate in Javascript
I'm having a function where I need to call another function which will be dynamic and I just know the fu开发者_StackOverflow中文版nction name.
For example, my function is
myfunction(obj){
otherfunction(?);
}
otherfunction
maybe
otherfunction(obj){
}
or
otherfunction(){
}
I don't know whether to pass the parameter or not.
How can I call the method?
you can call javascript functions with any count of arguments:
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
as you see all three method calls work although it is declared with 2 arguments
JavaScript does not actually require you to pass all the parameters to a function. Or any parameters. Or, you can pass more parameters than the function names in it's signature.
If the function defines a parameter, obj, but you just call it like
otherfunction();
Then obj is just undefined.
There isn't any way to get a function signature in JavaScript. However, you can just pass any arguments you may need, and the function will ignore them if it doesn't need them. It won't cause an error.
You can get the list of arguments passed to your function regardless of what you put in your function signature by looking at the arguments
local variable.
You can call a function with any number of arguments using the Function apply
method.
So to create a wrapper function that passes all its arguments onto the wrapped function:
function myfunction() {
otherfunction.apply(window, arguments);
}
Is this what you're trying to do?
(window
is the value that this
will be set to in the wrapped function; if you don't have a specific object you're calling a method on, the global window
object is normally used.)
you can use Functions as
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 !!!"));
精彩评论