一、bind、apply、call的相同点
- 都是为了重定向函数中this的指向。
- 三者的第一个参数都是this指向的对象。
- 三者都可以在后面加参数进行传参。
- bind、apply重定向参数不传,或者传null,undefined, 函数中的 this 指向 window 对象
二、bind、apply、call的异同
- bind返回的是个函数没有立即执行,apply、call立即执行。
- apply的参数是个数组。
- call的参数是多个值。
三、DEMO
1.apply
var array1 = [1,2,3,4,5];
var array2 = [5,4,3,2,1];
Array.prototype.push.apply(array1, array2);
console.log(array1)
// [1,2,3,4,5,5,4,3,2,1]
/*
*1.array.push的this重定向到array1
*2.array1立即执行push方法
*3.将array2的元素作为参数
* */
//等同于 array1.push(array2[0],array2[1],array2[2],array2[3],array2[4])
//等同于ES6 array1.push(...array2)
2.call
var array1 = [1,2,3,4,5];
Array.prototype.push.call(array1, 6,7,8,9);
console.log(array1.join(','))
// 1,2,3,4,5,6,7,8,9
/*
*1.array.push的this重定向到array1
*2.array1立即执行push方法
*3.将6,7,8,9作为参数
* */
//等同于 array1.push(6,7,8,9)
3.bind
var bar = function(){
console.log(this.x);
}
var foo = {
x:3
}
var sed = {
x:4
}
var func = bar.bind(foo).bind(sed);
func(); // 输出3,绑定的上下文是foo
var fiv = {
x:5
}
var func = bar.bind(foo).bind(sed).bind(fiv);
func(); // 输出3,绑定的上下文还是foo
四、运用场景
1.对象继承
function Animal(name,weight){
this.name = name;
this.weight = weight;
}
function Cat(){
Animal.call(this,'cat','50');
//Animal.apply(this,['cat','50']);
this.say = function(){
console.log("I am " +this.name+",my weight is " +this.weight);
}
}
var cat =new Cat();
cat.say();//I am cat,my weight is 50
网友评论