Javascript 如何执行作为参数传递给函数的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6001149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:49:31  来源:igfitidea点击:

How to execute a method passed as parameter to function

javascriptinvokemethod-invocation

提问by Muhammad Ummar

I want to write my own function in JavaScript which takes a callback method as a parameter and executes it after the completion, I don't know how to invoke a method in my method which is passed as an argument. Like Reflection.

我想在 JavaScript 中编写自己的函数,该函数将回调方法作为参数并在完成后执行,我不知道如何在我的方法中调用作为参数传递的方法。像反射。

example code

示例代码

function myfunction(param1, callbackfunction)
{
    //do processing here
    //how to invoke callbackfunction at this point?
}

//this is the function call to myfunction
myfunction("hello", function(){
   //call back method implementation here
});

回答by lonesomeday

You can just call it as a normal function:

您可以将其作为普通函数调用:

function myfunction(param1, callbackfunction)
{
    //do processing here
    callbackfunction();
}

The only extra thing is to mention context. If you want to be able to use the thiskeyword within your callback, you'll have to assign it. This is frequently desirable behaviour. For instance:

唯一额外的事情是提到context。如果您希望能够this在回调中使用关键字,则必须对其进行分配。这通常是可取的行为。例如:

function myfunction(param1, callbackfunction)
{
    //do processing here
    callbackfunction.call(param1);
}

In the callback, you can now access param1as this. See Function.call.

在回调中,您现在可以param1作为this. 见Function.call

回答by Kiran

I too came into same scenario where I have to call the function sent as parameter to another function.

我也遇到了同样的情况,我必须调用作为参数发送给另一个函数的函数。

I Tried

我试过

mainfunction('callThisFunction');

First Approach

第一种方法

function mainFuntion(functionName)
{
    functionName();
}

But ends up in errors. So I tried

但以错误告终。所以我试过了

Second Approach

第二种方法

functionName.call(). 

Still no use. So I tried

还是没用。所以我试过了

Third Approach

第三种方法

this[functionName]();

which worked like a champ. So This is to just add one more way of calling. May be there may be problem with my First and Second approaches, but instead googling more and spending time I went for Third Approach.

这就像一个冠军。所以这只是增加了一种调用方式。可能我的第一种和第二种方法可能有问题,但我更多地使用谷歌搜索并花时间选择了第三种方法。

回答by Roki

function myfunction(param1, callbackfunction)
{
    //do processing here
   callbackfunction(); // or if you want scoped call, callbackfunction.call(scope)
}

回答by Moises D

object[functionName]();

object[functionName]();

object:refers to the name of the object.

object:对象的名称。

functionName:is a variable whose value we will use to call a function.

functionName:是一个变量,我们将使用其值来调用函数。

by putting the variable used to refer to the function name inside the []and the ()outside the bracket we can dynamically call the object's function using the variable. Dot notation does not work because it thinks that 'functionName' is the actual name of the function and not the value that 'functionName' holds. This drove me crazy for a little bit, until I came across this site. I am glad stackoverflow.com exists <3

通过将用于引用函数名称的变量放在[] 内,将()放在括号外,我们可以使用该变量动态调用对象的函数。点表示法不起作用,因为它认为“functionName”是函数的实际名称,而不是“functionName”持有的值。这让我有点发疯,直到我遇到了这个网站。我很高兴 stackoverflow.com 存在 <3

回答by Ross

Super basic implementation for my use case based on some excellent answers and resources above:

我的用例的超级基本实现基于上面一些优秀的答案和资源:

/** Returns the name of type member in a type-safe manner. **(UNTESTED)** e.g.:
*
* ```typescript
* nameof<Apple>(apple => apple.colour); // Returns 'colour'
* nameof<Apple>(x => x.colour); // Returns 'colour'
* ```
*/
export function nameof<T>(func?: (obj: T) => any): string {
 const lambda = ' => ';
 const funcStr = func.toString();

 const indexOfLambda = funcStr.indexOf(lambda);
 const member = funcStr.replace(funcStr.substring(0, indexOfLambda) + '.', '').replace(funcStr.substring(0, indexOfLambda) + lambda, '');

 return member;
}

回答by stivlo

Another way is to declare your function as anonymous function and save it in a variable:

另一种方法是将您的函数声明为匿名函数并将其保存在一个变量中:

var aFunction = function () {
};

After that you can pass aFunction as argument myfunction and call it normally.

之后,您可以将 aFunction 作为参数 myfunction 传递并正常调用它。

function myfunction(callbackfunction) {
    callbackfunction();
}

myfunction(aFunction);

However, as other answers have pointed out, is not necessary, since you can directly use the function name. I will keep the answer as is, because of the discussion that follows in the comments.

但是,正如其他答案所指出的那样,没有必要,因为您可以直接使用函数名称。由于评论中的讨论,我将保持答案不变。

回答by jcromeros1987

I will do something like this

我会做这样的事情

var callbackfunction = function(param1, param2){
console.log(param1 + ' ' + param2)
}

myfunction = function(_function, _params){
_function(_params['firstParam'], _params['secondParam']);
}

Into the main code block, It is possible pass parameters

进入主代码块,可以传参数

myfunction(callbackfunction, {firstParam: 'hello', secondParam: 'good bye'});

回答by SharpC

All the examples here seem to show how to declare it, but not how to use it. I think that's also why @Kiran had so many issues.

这里的所有例子似乎都展示了如何声明它,但没有展示如何使用它。我认为这也是@Kiran 有这么多问题的原因。

The trick is to declare the function which uses a callback:

诀窍是声明使用回调的函数:

function doThisFirst(someParameter,  myCallbackFunction) {
    // Do stuff first
    alert('Doing stuff...');

    // Now call the function passed in
    myCallbackFunction(someParameter);
}

The someParameterbit can be omitted if not required.

someParameter如果不需要,可以省略该位。

You can then use the callback as follows:

然后,您可以按如下方式使用回调:

doThisFirst(1, myOtherFunction1);
doThisFirst(2, myOtherFunction2);

function myOtherFunction1(inputParam) {
    alert('myOtherFunction1: ' + inputParam);
}

function myOtherFunction2(inputParam) {
    alert('myOtherFunction2: ' + inputParam);
}

Note how the callback function is passed in and declared without quotes or brackets.

请注意回调函数是如何在没有引号或括号的情况下传入和声明的。

  • If you use doThisFirst(1, 'myOtherFunction1');it will fail.
  • If you use doThisFirst(1, myOtherFunction3());(I know there's no parameter input in this case) then it will call myOtherFunction3firstso you get unintended side effects.
  • 如果你使用doThisFirst(1, 'myOtherFunction1');它会失败。
  • 如果您使用doThisFirst(1, myOtherFunction3());(我知道在这种情况下没有参数输入),那么它将myOtherFunction3首先调用,因此您会得到意想不到的副作用。