Actually, your code will pretty much work as is, just declare your callback as an argument and you can call it directly using the argument name.
(实际上,您的代码将按原样工作,只需将您的回调声明为参数,您可以使用参数名称直接调用它。)
The basics(基础)
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);
That will call doSomething
, which will call foo
, which will alert "stuff goes here".
(这将调用doSomething
,它将调用foo
,它会提醒“东西在这里”。)
Note that it's very important to pass the function reference ( foo
), rather than calling the function and passing its result ( foo()
).
(请注意,传递函数引用 ( foo
)非常重要,而不是调用函数并传递其结果( foo()
)。)
In your question, you do it properly, but it's just worth pointing out because it's a common error.(在你的问题中,你做得很好,但值得指出,因为这是一个常见的错误。)
More advanced stuff(更先进的东西)
Sometimes you want to call the callback so it sees a specific value for this
.
(有时你想调用回调所以它看到的特定值this
。)
You can easily do that with the JavaScript call
function:(您可以使用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`
You can also pass arguments:
(你也可以传递参数:)
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`
Sometimes it's useful to pass the arguments you want to give the callback as an array, rather than individually.
(有时,传递您想要将回调作为数组的参数,而不是单独传递是有用的。)
You can use apply
to do that:(你可以使用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`