内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我所需要做的就是在当前函数执行结束时执行回调函数。
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
。
请注意,传递函数非常重要,具体请参照(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`