请针对call apply bind举例
时间: 2024-05-01 21:21:22 浏览: 84
`call`、`apply`和`bind`是JavaScript中的三个重要的函数方法,它们都可以用来绑定函数中的`this`关键字。
`call`和`apply`都是立即调用函数,而`bind`则是返回一个新的函数,可稍后调用。
下面是三个函数的示例:
```
// call
const person1 = { name: 'Alice', age: 25 };
const person2 = { name: 'Bob', age: 30 };
function greet() {
console.log(`Hello, ${this.name}. You are ${this.age} years old.`);
}
greet.call(person1); // Hello, Alice. You are 25 years old.
greet.call(person2); // Hello, Bob. You are 30 years old.
// apply
const numbers = [5, 10, 15, 20];
function sumNumbers(a, b, c, d) {
return a + b + c + d;
}
const result = sumNumbers.apply(null, numbers);
console.log(result); // 50
// bind
const person = { name: 'Mike', age: 35 };
function logPerson(job, hobbies) {
console.log(`${this.name} is ${this.age} years old and works as a ${job}. ${this.name} likes ${hobbies.join(', ')}.`);
}
const logPersonBind = logPerson.bind(person);
logPersonBind('developer', ['reading', 'swimming']); // Mike is 35 years old and works as a developer. Mike likes reading, swimming.
```
在上面的示例中,`call`的作用是将函数`greet`中的`this`关键字绑定到`person1`和`person2`对象上。
`apply`可以将一个数组作为参数传给函数。在上面的示例中,`numbers`数组作为参数传递给`sumNumbers`函数。
`bind`创建一个新的函数,将`this`关键字绑定到`person`对象上,并返回一个新的函数`logPersonBind`。稍后执行`logPersonBind`函数时,`this`关键字将始终指向`person`对象。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)