DEV Community

Discussion on: Javascript call and apply 101

Collapse
 
iggredible profile image
Igor Irianto • 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);
        }
    };
}());
Enter fullscreen mode Exit fullscreen mode
  • 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;  }};
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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