When should I use call() vs invoking the function directly?

后端 未结 6 2276
小蘑菇
小蘑菇 2021-02-19 05:14

I\'ve got a JavaScript application that uses a lot of callbacks. A typical function will take a callback, and wrap it with another callback.

Namespace.foo = func         


        
6条回答
  •  后悔当初
    2021-02-19 05:47

    A good example is when implementing a function that needs a callback. When writing OO code, you want to allow the caller to specify the context that a callback will be called.

    function validateFormAjax(form, callback, context) {
      // Using jQuery for simplicity
      $.ajax({
        url: '/validateForm.php',
        data: getFormData(form),
        success: function(data) {
          callback.call(context, data);
        }
      });
    }
    

    Note that my example could just be implemented by passing the context parameter to the $.ajax call, but that wouldn't show you much about using call

提交回复
热议问题