JavaScript bind
apply
call
的使用
与区别
1. Function.prototype.bind()
bind()
方法创建一个新的函数,在bind()
被调用时,这个新函数的this
被指定为bind()
的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
const getX =function() {
return this.x;
}
const module = {
x: 42
};
console.log(getX()); // => undefined
const boundGetX = getX.bind(module);
console.log(boundGetX()); // => 42
2. Function.prototype.apply()
apply()
方法调用一个具有给定this
值的函数,以及以一个数组(或类数组对象)的形式提供的参数。
const numbers = [5, 6, 2, 3, 7];
const max = Math.max.apply(null, numbers);
console.log(max); // => 7
const min = Math.min.apply(null, numbers);
console.log(min); // => 2
3. Function.prototype.call()
call()
方法使用一个指定的this
值和单独给出的一个或多个参数来调用一个函数。
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
console.log(new Food('noodles', 8).name); // => "noodles"
4. bind
, call
, apply
的区别
bind
是只改变函数内部this
指向, 但不自调用call
,apply
改变函数内部this
指向, 并且自调用
5. 可考虑使用 箭头函数
使 this
与封闭词法环境的 this
保持一致
在箭头函数中,this与封闭词法环境的this保持一致。在全局代码中,它将被设置为全局对象
var marker = this;
var fn = (() => this);
console.log(fn() === marker); // => true
// 作为对象的一个方法调用
var obj = {prop: fn};
console.log(obj.prop() === marker); // true
// 尝试使用call来设定this
console.log(fn.call(obj) === marker); // true
// 尝试使用bind来设定this
fn = fn.bind(obj);
console.log(fn() === marker); // true
无论如何,fn
的 this
被设置为他被创建时的环境