Veverke
Veverke

Reputation: 11358

Is there a case where using bind would not cover the need for using either call or apply?

I am learning javascript via javascript.info. I learned about bind (and a lesson before about call and apply) I see this post inquires about the differences on all 3.

After reading all that, I wonder: is there a scenario where using bind would NOT cover the need for using either call or apply ? I mean, call or apply are meant for calling the function immediately. bind - later on.

Would not the following work in all cases?

let f = function(){/* code here */};
let errorFreeF = f.bind(myContextObj);
errorFreeF(); 

A less verbose snippet:

function(){/* code here */}.bind(myContextObj)();

If the answer is using bind is always safe and indeed covers all scenarios, seems like the call/apply could be deprecated in future JS versions ? Or it performs worse?

Upvotes: 1

Views: 32

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370739

You can use .bind as a substitute for .call and .apply. If you wanted, you could convert all uses of .call and .apply with .bind.

The other combinations are true as well. If you really wanted to, you could also replace all instances of those methods with .call, or with .apply.

It's just that it's sometimes inelegant to do so. For similar reasons, even though Array.prototype.forEach could be used to identify an element which matches a condition in an array, Array.prototype.find is more appropriate and requires less code.

seems like the call/apply could be deprecated in future JS versions ?

No, for a few reasons:

  • They're useful methods to have (they can result in cleaner code than having to write the same thing with .bind)
  • Using .bind creates a function. In rare cases, the extra overhead resulting from the creation of a function may be a problem. (But .call and .apply only invoke functions, they don't create functions)
  • The language designers will never implement a change (such as removing .call or .apply) because that will break existing websites, which is avoided at all costs.

Upvotes: 2

Related Questions