In JavaScript, the call
, apply
, and bind
methods are used to change the this
context of a function.
const person = {
name: 'John',
greet: function(age) {
return `Hello, my name is ${this.name} and I'm ${age} years old.`;
}
};
const anotherPerson = { name: 'Jane' };
// Using call
console.log(person.greet.call(anotherPerson, 25)); // Hello, my name is Jane and I'm 25 years old.
// Using apply
console.log(person.greet.apply(anotherPerson, [30])); // Hello, my name is Jane and I'm 30 years old.
// Using bind
const boundGreet = person.greet.bind(anotherPerson);
console.log(boundGreet(35)); // Hello, my name is Jane and I'm 35 years old.
A factorial of a number is the product of all positive integers less than or equal to that number. Here's an example of how to find the factorial of a number:
function factorial(n) {
if (n === 0 || n === 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120