Thursday, September 30, 2021

why to use call, apply and bind 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 .
How can we borrow method for another object?

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');

apply() → arguments as array

john.presentation.apply(smith, ['friendly', 'evening']);

bind() → creates a new function

var smithPresentation = john.presentation.bind(smith);

smithPresentation('formal', 'morning');

bind() does not execute immediately.



No comments:

Post a Comment

Javascript module

JavaScript Modules (ES6) let you split code into multiple files and reuse code cleanly. Main keywords: export → make something available...