DEV Community

Discussion on: Javascript call and apply 101

iggredible profile image
Igor Irianto Author • Edited on

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() {
    return {
        id: 123,
        publicFn: function() {
  • 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.age, this.getIdNumber() and here **this** is pointing to Dave
            return "Ticket is booked for "+ + ", " + 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 =, place, numberOfPeople, paymentDetails);

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