JS Call: принципы и применение в веб-разработке
JavaScript Call
JavaScript Call is a method that is used to invoke functions or object methods with a specified value of this and arguments. It allows passing execution context, which is an object that will be used as this inside the function.
The syntax of the Call method looks like this:
function.call(thisArg, arg1, arg2, ...)
Where:
thisArg: The value that will be contained in this inside the called function. It can be an object or a primitive value.arg1, arg2, ...: The parameters that will be passed to the called function.
Let's consider an example of using the Call method in practice. Imagine that we have an object "person" with two properties: "name" and "age". We will also define a function "greet" that will display a greeting using these properties:
const person = {
name: "John",
age: 30
};
function greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
greet(); // Output: "Hello, my name is undefined and I am undefined years old."
If we call the "greet" function without a context, the values of this.name and this.age will be undefined. However, we can use the Call method to explicitly specify where to take the values for this:
greet.call(person); // Output: "Hello, my name is John and I am 30 years old."
Now the "greet" function invocation uses the "person" object as the context, and all the variables this.name and this.age have their corresponding values.
The Call method also allows passing additional arguments to the called function. Let's modify our "greet" function to accept a "city" parameter:
function greet(city) {
console.log(`Hello from ${city}! My name is ${this.name} and I am ${this.age} years old.`)
}
greet.call(person, "Moscow"); // Output: "Hello from Moscow! My name is John and I am 30 years old."
The Call method allows us to explicitly specify the value of this and pass arguments inside the function. This is very useful when working with functions that require a specific context or arguments to function correctly.
Note that when using the Call method, the context of the called function will be temporarily changed only for that particular call.