Thursday, September 30, 2021

why to use call method in Javascript?

 let's look at an example ,

var john = {

    name: 'john',

    job: 'engineer',

    age: 35,

    presentation: function (style, timeOffDay) {

        if (style === 'formal') {

            console.log('Good ' + timeOffDay + ',ladies and gentlemen i\'m ' + this.name + ' working as ' + this.job + ' and i\'m ' + this.age + ' years old');

        } else if (style === 'friendly') {

            console.log('Good ' + timeOffDay + ',ladies and gentlemen i\'m ' + this.name + ' working as ' + this.job + ' and i\'m ' + this.age + ' years old');


        }

    }

};

john.presentation('formal','morning');

var smith={

    name:'smith',

    job:'teacher',

    age:40

};

john.presentation.call(smith,'friendly','evening');

Here,john is an object which have a method presentation . Now we have created another object smith without any method .But i don't want to create new method for smith object but want to use method of john object .
So,what can we to do achive this?
We can borrow method of john by calling call method and setting this variable to smith as the first argument.

john.presentation.call(smith,'friendly','evening');



No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...