bind apply call区别
时间: 2024-10-12 08:10:27 浏览: 43
在JavaScript中,`bind()`, `apply()`, 和 `call()` 都是用来改变函数内部 `this` 关键字指向的对象,但它们之间有细微的区别:
1. **bind()**:它返回一个新的函数,这个新函数拥有指定的上下文(即 this 的值)。当你调用这个新的函数时,它的 `this` 就绑定到你提供的上下文中。例如:
```javascript
const obj = {name: 'John'};
const func = function() {
console.log(this.name);
};
const boundFunc = func.bind(obj); // boundFunc 的 this 现在关联到 obj
boundFunc(); // 输出 "John"
```
2. **apply()**:它接收两个参数,第一个参数是要作为 `this` 的对象,第二个参数是一个数组,包含了函数需要的所有参数。`apply()` 直接修改了当前函数内部的 `arguments` 对象。例如:
```javascript
func.apply(obj, ['Doe']); // 这里 'Doe' 替换了原函数中的 this.name
```
3. **call()**:与 `apply()` 类似,`call()` 也接受两个参数,第一个参数是 `this` 的值,第二个参数是传给函数的实际参数数组。但它会创建一个新的执行上下文,而不是直接操作 `arguments`。例如:
```javascript
func.call(obj, 'Doe'); // 相同效果,将 'Doe' 绑定为 this,并调用 func
```
阅读全文
相关推荐


















