实际上,您的代码将按原样工作,只需将回调声明为参数即可,您可以使用参数名称直接调用它。
基础
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
。您可以使用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`
object.LoadData(success)
调用必须在function success
定义之后。否则,您将收到一条错误消息,告诉您该函数未定义。