实际上,您的代码几乎可以按原样工作,只需将您的回调声明为参数,您就可以使用参数名称直接调用它。
基础
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
,它会提醒“东西到这里了”。
请注意,传递函数引用( foo
)非常重要,而不是调用函数并传递其结果 ( foo()
)。在您的问题中,您做得对,但值得指出,因为这是一个常见错误。
更高级的东西
有时您想调用回调,以便它看到 的特定值this
。您可以使用 JavaScriptcall
函数轻松做到这一点:
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`