我需要做的就是在我当前的函数执行结束时执行一个回调函数。
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,这将提醒“东西在这里”。
doSomething
foo
请注意,传递函数 引用 (foo)非常重要,而不是调用函数并传递其结果(foo())。在您的问题中,您做得正确,但值得指出的是,因为这是一个常见错误。
foo()
有时您想调用回调,以便它看到this. call您可以使用 JavaScript函数轻松做到这一点:
this
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来做到这一点:
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`