返回
函数bind、call、apply区别与用法
前端
2023-10-20 05:31:59
bind、call、apply 的区别
方法 | 语法 | 作用 |
---|---|---|
bind | func.bind(thisArg, ...args) |
返回一个新的函数,该函数的 this 指向被绑定为 thisArg,并且可以传递任意数量的参数 |
call | func.call(thisArg, ...args) |
立即执行函数,并将其 this 指向设置为 thisArg,可以传递任意数量的参数 |
apply | func.apply(thisArg, [args]) |
立即执行函数,并将其 this 指向设置为 thisArg,参数必须是一个数组 |
bind、call、apply 的用法
bind
bind 方法返回一个新的函数,该函数的 this 指向被绑定为 thisArg,并且可以传递任意数量的参数。新函数的执行不会立即发生,而是在以后的某个时间点被调用。
const obj = {
name: 'John Doe',
getName: function() {
return this.name;
}
};
const boundGetName = obj.getName.bind(obj);
console.log(boundGetName()); // "John Doe"
call
call 方法立即执行函数,并将其 this 指向设置为 thisArg,可以传递任意数量的参数。
const obj = {
name: 'John Doe',
getName: function() {
return this.name;
}
};
console.log(obj.getName.call(obj)); // "John Doe"
apply
apply 方法立即执行函数,并将其 this 指向设置为 thisArg,参数必须是一个数组。
const obj = {
name: 'John Doe',
getName: function() {
return this.name;
}
};
console.log(obj.getName.apply(obj, [])); // "John Doe"
bind、call、apply 的选择
在实际开发中,我们应该根据具体情况选择使用 bind、call 还是 apply。
- 如果需要创建一个新的函数,并且希望该函数的 this 指向被绑定为某个对象,那么可以使用 bind。
- 如果需要立即执行一个函数,并且希望该函数的 this 指向被绑定为某个对象,那么可以使用 call 或 apply。
- 如果需要立即执行一个函数,并且希望该函数的参数是一个数组,那么可以使用 apply。
总结
bind、call 和 apply 是 JavaScript 中非常重要的函数调用方法,它们可以改变函数的 this 指向,从而实现不同的调用效果。希望本文能够帮助您更好地理解和使用它们。