创建一个Javascript回调函数?

fab*_*ian 5 javascript

我想知道如何在这段代码中实现回调

MyClass.myMethod("sth.", myCallback);
function myCallback() { // do sth };
Run Code Online (Sandbox Code Playgroud)
var MyClass = {

myMethod : function(params, callback) {

    // do some stuff

    FB.method: 'sth.',
       'perms': 'sth.'
       'display': 'iframe'
      },
      function(response) {

            if (response.perms != null) {
                // How to pass response to callback ?
            } else {
                // How to pass response to callback ?
            }
      });
}
Run Code Online (Sandbox Code Playgroud)

}

jen*_*ing 13

有三种方法可以实现"//如何将响应传递给回调?" :

  1. callback(response, otherArg1, otherArg2);
  2. callback.call(this, response, otherArg1, otherArg2);
  3. callback.apply(this, [response, otherArg1, otherArg2]);

1是最简单的,2是你想要控制this回调函数中的' '变量值,而3类似于2,但你可以传递可变数量的参数callback.

这是一个不错的参考:http://odetocode.com/Blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx


Pet*_*r C 7

您所要做的就是以正常方式调用回调函数.在这种情况下,你会这样做callback(response).

var MyClass = {

myMethod : function(params, callback) {

// do some stuff

FB.method: { 'sth.',
   'perms': 'sth.'
   'display': 'iframe'
  },
  function(response) {

        if (response.perms != null) {
            // How to pass response to callback ?
            // Easy as:
            callback(response);
        } else {
            // How to pass response to callback ?
            // Again:
            callback(response);
        }
  });
}

}
Run Code Online (Sandbox Code Playgroud)