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 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! 😁
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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:
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):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)
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
Hope this makes sense. Let me know if I can help answer any other question! 😁