我需要做的就是在当前函数执行结束时执行一个回调函数。
function LoadData()
{
alert('The data has been loaded');
//Call my callback with parameters. For example,
//callback(loadedData , currentObject);
}
这个函数的消费者应该是这样的:
object.LoadData(success);
function success(loadedData , currentObject)
{
//Todo: some action here
}
我该如何实现?
最佳答案
实际上,您的代码几乎可以按原样运行,只需将您的回调声明为参数,您就可以使用参数名称直接调用它。
基础知识
function doSomething(callback) {
// ...
// Call the callback
callback('stuff', 'goes', 'here');
}
function foo(a, b, c) {
// I'm the callback
alert(a + " " + b + " " + c);
}
doSomething(foo);
这将调用 doSomething
,它会调用 foo
,它会提醒“stuff goes here”。
请注意,传递函数reference (foo
) 非常重要,而不是调用函数并传递其结果 (foo()
)。在您的问题中,您做得正确,但值得指出,因为这是一个常见错误。
更高级的东西
有时您想调用回调,以便它看到 this
的特定值。您可以使用 JavaScript call
函数轻松做到这一点:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.call(this);
}
function foo() {
alert(this.name);
}
var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Joe" via `foo`
你也可以传递参数:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback, salutation) {
// Call our callback, but using our own instance as the context
callback.call(this, salutation);
}
function foo(salutation) {
alert(salutation + " " + this.name);
}
var t = new Thing('Joe');
t.doSomething(foo, 'Hi'); // Alerts "Hi Joe" via `foo`
有时,将您想要作为回调函数的参数作为数组而不是单独传递是很有用的。您可以使用 apply
来做到这一点:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.apply(this, ['Hi', 3, 2, 1]);
}
function foo(salutation, three, two, one) {
alert(salutation + " " + this.name + " - " + three + " " + two + " " + one);
}
var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Hi Joe - 3 2 1" via `foo`
关于javascript - 在 JavaScript 中创建自定义回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2190850/