如何执行作为参数传递给函数的方法 [英] How to execute a method passed as parameter to function

查看:156
本文介绍了如何执行作为参数传递给函数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

示例代码

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


推荐答案

您可以将其称为正常功能:

You can just call it as a normal function:

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

唯一需要提及的是 context 。如果您希望能够在回调中使用关键字,则必须分配它。这通常是理想的行为。例如:

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

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

在回调中,您现在可以访问 param1 as this 。请参阅 Function.call

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

这篇关于如何执行作为参数传递给函数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆