# bind call apply的区别
共同点都是改变this的指向。
# bind
bind() 会创建新的函数,这个新函数的this
指向bind()
的第一个参数。
// 示例
let corgi = {
type: "dog"
}
const animal = {
type: "default",
getType: function() {
return this.type;
}
}
console.log(animal.getType());
// output: default
const newFn = animal.getType.bind(corgi);
console.log(newFn());
// output: dog
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# call
call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用
一个函数。
console.log(animal.getType.call(corgi));
// output: dog
1
2
2
# apply
apply() 方法调用一个具有给定this值的函数,以及作为一个数组(或类似数组对象)提供的参数。
与call()
类似,不过apply()
是以数组形式传递参数
console.log(animal.getType.apply(corgi, [...params]));
// output: dog
1
2
2