call(), apply(), and bind() methods in JavaScript - #6

Published: 22 March 2024
on channel: Everyday Be Coding
45
7

In JavaScript, the call(), apply(), and bind() methods are used to manipulate the execution context of functions. They allow you to explicitly specify the value of this and pass arguments to a function when invoking it. Here's a brief overview of each:

call() Method:
The call() method invokes a function with a specified this value and arguments provided individually.

Syntax: function.call(thisArg, arg1, arg2, ...)

Example:
function greet() {
return "Hello, " + this.name;
}

var person = { name: "John" };
console.log(greet.call(person)); // Output: Hello, John

apply() Method:
The apply() method is similar to call(), but it accepts arguments as an array or an array-like object.

Syntax: function.apply(thisArg, [argsArray])

Example:
function greet(greeting) {
return greeting + ", " + this.name;
}

var person = { name: "John" };
console.log(greet.apply(person, ["Hello"])); // Output: Hello, John

bind() Method:
The bind() method creates a new function with the same body as the original function but with a specified this value.

Unlike call() and apply(), bind() does not immediately invoke the function; instead, it returns a new function with the bound this value.

Syntax: function.bind(thisArg[, arg1[, arg2[, ...]]])

Example:
function greet(greeting) {
return greeting + ", " + this.name;
}

var person = { name: "John" };
var boundGreet = greet.bind(person, "Hello");

console.log(boundGreet()); // Output: Hello, John
In this example, bind() creates a new function boundGreet, which always has person as its this value and "Hello" as its first argument.

These methods are particularly useful when you want to borrow methods from other objects, set the context for callback functions, or create functions with predefined arguments.

Chapter :
00:00 Introduction
00:26 Call Method
01:16 Apply Method
01:50 Bind Method
02:31 Summery


Thank you for watching this Video.
Everyday Be coding


On this page of the site you can watch the video online call(), apply(), and bind() methods in JavaScript - #6 with a duration of hours minute second in good quality, which was uploaded by the user Everyday Be Coding 22 March 2024, share the link with friends and acquaintances, this video has already been watched 45 times on youtube and it was liked by 7 viewers. Enjoy your viewing!