Middle
What methods of working with context (this) exist? What is the signature of the call method? How does call differ from apply?
sobes.tech AI
Answer from AI
In JavaScript, the context (this) is determined by how a function is called. The main methods for working with context:
- call — calls a function with a specified context and arguments passed one by one.
- apply — similar to call, but arguments are passed as an array.
- bind — returns a new function with a bound context, which can be called later.
Signature of the call method:
func.call(thisArg, arg1, arg2, ...)
The difference between call and apply in how arguments are passed:
- call takes arguments separated by commas
- apply takes an array of arguments
Example:
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'Ivan' };
greet.call(person, 'Hello', '!'); // Hello, Ivan!
greet.apply(person, ['Hello', '.']); // Hello, Ivan.