实际上,您的代码几乎可以按原样运行,只需将您的回调声明为参数,您就可以使用参数名称直接调用它。
基础知识
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 going 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`