In JavaScript, the call, apply, and bind methods are used to change the this context of a function.
The call method is used to invoke a function and specify the this context. It takes an object as its first argument, which becomes the this context for the function, followed by any additional arguments for the function.
For example:
function total(eng,mat) { console.log(this.name+" got "+(eng+mat)+" Marks"); } const user = { name: 'Ram' }; total.call(user, 65,75); // Ram got 140 Marks
The apply method is similar to call, but it takes an array of arguments for the function, instead of a list of arguments.
For example:
function total(eng,mat) { console.log(this.name+" got "+(eng+mat)+" Marks"); } const user = { name: 'Ram' }; total.apply(user, [65,75]); // Ram got 140 Marks
The bind method is used to create a new function with the this context set to the provided object. It takes an object as its first argument, which becomes the this context for the new function, and any additional arguments for the function are passed as arguments to the new function.
For example:
function total(eng,mat) { console.log(this.name+" got "+(eng+mat)+" Marks"); } const user = { name: 'Ram' }; const fun=total.bind(user, 65,75); fun();// Ram got 140 Marks
In this way, call, apply and bind methods are used to change the this context of a function, which allows for greater flexibility and reusability of code.
In conclusion, understanding and mastering the use of the call, apply, and bind methods in JavaScript is an important aspect of object-oriented programming. These methods allow you to change the this context of a function, enabling greater flexibility and reusability of code. With the ability to invoke a function with a specific context, pass an array of arguments, and create a new function with a pre-defined context, you will be able to write more efficient and maintainable code. Understanding these methods is essential for any JavaScript developer who wants to take their skills to the next level.
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions