DEV Community

Discussion on: Javascript call and apply 101

Collapse
kristoftombacz profile image
kristoftombacz

i read a lot of article about call and apply, but still didnt get the idea WHY to use it. why should i introduce these methods to the project (which might be unknown for some), when i can write less, but a more straightforward code?

your example for call is the following

const breakfastObj = {
  food: 'blueberry waffles',
  drink: 'orange juice'
}

function sayBreakfast(){
  console.log(`I had ${this.food} and ${this.drink} for breakfast`)
}

sayBreakfast.call(breakfastObj)

instead of this, why shouldnt i just write

function sayBreakfast({ food, drink }){
  console.log(`I had ${food} and ${drink} for breakfast`)
}

sayBreakfast(breakfastObj)

am i missing something?

Collapse
ytjchan profile image
ytjchan

I'd also avoid this as much as possible...

Collapse
iggredible profile image
Igor Irianto Author • Edited

Hey kristoftombacz , thanks for replying!

That's a good question, thanks for bringing it up! I used that example because I think that is easiest to understand/ to make a point. I aimed this article for simplicity, I apologize for not being the most practical.

As for the real life application, here are two, I am sure there are myriads more:

  • Scoping

What if you want to call private function but don't want to expose it to public? We can use call. Here is an example (source):

var obj = (function() {
    var privateFn = function() {
        alert(this.id);
    }
    return {
        id: 123,
        publicFn: function() {
            privateFn.call(this);
        }
    };
}());
  • Object reuse

What if you have an object that you later decide, "hey, this is useful, I want to extend this object to use with other attributes!".

Here is another example (souce)

var Dave = {
    name : 'Dave',
    age    : '30',
    getIdNumber: function(){
        return 'id number of dave';   },
    bookCheapFlightTickets: function( place, numberOfPeople, paymentDetails ){
        function sendSecretCode(){
            // Dave's own logic for generating secret code
            // and sending to his friends
            // ...      }
        function bookTickets(){
            // book the tickets using the given details
            // the ticket will be printed always in this.name , this.age, this.getIdNumber() and here **this** is pointing to Dave
            return "Ticket is booked for "+ this.name + ", " + this.age +", "+ this.getIdNumber();
        }
        var isVerified = sendSecretCode();
        return isVerified ? bookTickets() : false;  }};

And instead of rewriting the object and going through a lot of headache (say this Dave object has been around for years - who knows where else it is being used and who knows what will break if we modify it? 😅) If I want to rewrite one, that does not sound DRY. Instead I could do something like

var Iggy = {
    name: 'Iggy',
    age:    '29',
    getIdNumber: function(){
        return 'your id number';  }}
...
var davesMethodForFlightBooking = Dave.bookCheapFlightTickets;
// using call
var bookedTicket = davesMethodForFlightBooking.call(Iggy, place, numberOfPeople, paymentDetails);

Hope this makes sense. Let me know if I can help answer any other question! 😁