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

半腔热情 提交于 2019-12-03 23:57:17
Joe

call() is used to change the this value of the function:

var obj = {a: 0};
method.call(obj, "parameter");
function method(para) {
    this.a == 0; // true <-- obj is now this
}

The only reason to use call (or apply) is if you want to set the value of this inside the function.

Well, I guess apply can be useful in other cases as it accepts an array of parameters.

Using a function's call() method allows you to changed the object that's bound to the function as this during the execution of the function - this is also called the context

their_on_success.call(myContext, results)

But, if your callback function does not depend on this, it make no difference which way you call it.

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

Another case for using call() is when you are in an environment where you can't trust the object's own method hasn't been replaced or you know it doesn't actually have the method you want to run on it. hasOwnProperty is often such a method - there are many places where javascript objects may not have their own hasOwnProperty method so invoking it as hasOwnProperty.call(obj, propertyName) is prudent.

One scenario I often use "call" is splice arguments:

const fn = function() {
    const args = Array.prototype.slice.call(arguments, 0);
    console.log(args);
}

Notice that arguments is an object. the args however is an array.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!