创建一个Javascript回调函数?

时间:2011-02-24 22:33:10

标签: javascript

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

MyClass.myMethod("sth.", myCallback);
function myCallback() { // do sth };

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 ?
            }
      });
}

}

9 个答案:

答案 0 :(得分:13)

实现“//如何将响应传递给回调?”的三种方法:

  1. callback(response, otherArg1, otherArg2);
  2. callback.call(this, response, otherArg1, otherArg2);
  3. callback.apply(this, [response, otherArg1, otherArg2]);
  4. 1是最简单的,2是在你想要控制回调函数中的'this'变量的值,而3类似于2,但是你可以将可变数量的参数传递给{{1 }}

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

答案 1 :(得分:6)

您所要做的就是以正常方式调用回调函数。在这种情况下,您只需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);
        }
  });
}

}

答案 2 :(得分:1)

只需调用传入的函数。

callback(response)

答案 3 :(得分:1)

我认为您可以在那里简单地拨打callback(response.perms)。您也可以将其注册为

班级成员:

  MyClass.cb = callback;

后来称之为:

 MyClass.cb(response.perms)

答案 4 :(得分:1)

你很接近......只需使用回调。在这种情况下,您可以形成一个闭包。

var MyClass = {

myMethod : function(params, callback) {

    // do some stuff

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

            if (response.perms != null) {
                callback(response);
            } else {
                // response is null, but you can pass it the same as you did above - if you want to.  Probably better to have a generic failure handler
                ajaxFailHandler();
            }
      });
}

答案 5 :(得分:0)

callback.call(null, response);

答案 6 :(得分:0)

MyClass.myMethod("sth.", myCallback);
var myCallback = function myCallback() { // do sth }

var MyClass = {

myMethod : function(params, callback) {

    // do some stuff

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

            if (response.perms != null) {
                callback();
            } else {
                callback();
            }
      });
}

}

答案 7 :(得分:-1)

你现在有了对某个功能的引用。只需调用它:

callback(response.perms);

答案 8 :(得分:-3)


var callback = function() {

};

多数民众赞成: - )