call apply bind的异同
1. 定义
- Function.prototype.
call()方法使用一个指定的this值和单独给出的一个或多个参数来调用一个函数 - Function.prototype.
apply()方法调用一个具有给定this值的函数,以及以一个数组(或类数组对象)的形式提供的参数 - Function.prototype.
bind()方法创建一个新的函数,在 bind() 被调用时,这个新函数的this被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用
2. 手写函数——修改this指向
//1.apply function bindThis(f, oTarget) { return function(){ return f.apply(oTarget, arguments); } } //2.call function bindThis(f,oTarget){ return function(){ return f.call(oTarget,...arguments); } } //3.bind function bindThis(f,oTarget){ return function(){ return f.bind(oTarget,...arguments)(); } } //或简写为: function bindThis(f,oTarget){ return function(){ return f.bind(oTarget); } }
3. 相同点:
- 都是用来改变函数的this对象的指向的
- 第一个参数都是this要指向的对象
- 都可以利用后续参数传参
4. 区别:
- call()方法接受的是一个参数列表,而 apply() 方法接受的是一个包含多个参数的数组
- bind() 是返回绑定this之后的函数,便于稍后调用;apply() 、call()则是立即执行
1 var xw = { 2 name : "小王", 3 gender : "男", 4 age : 24, 5 say : function(school, grade) { 6 console.log(this.name + " , " + this.gender + " ,今年" + this.age + " ,在" + school + "上" + grade ); 7 } 8 } 9 var xh = { 10 name : "小红", 11 gender : "女", 12 age : 18 13 } 14 xw.say.call(xh,"实验小学","六年级"); // "小红 , 女 ,今年18 ,在实验小学上六年级" 15 xw.say.apply(xh,["实验小学","六年级郑州牛皮癣医院"]); // "小红 , 女 ,今年18 ,在实验小学上六年级郑州牛皮癣医院" 16 xw.say.bind(xh,"实验小学","六年级")(); // "小红 , 女 ,今年18 ,在实验小学上六年级" 17 xw.say.bind(xh)("实验小学","六年级"); // "小红 , 女 ,今年18 ,在实验小学上六年级"
1 var xw = { 2 name : "小王", 3 gender : "男", 4 age : 24, 5 say : function() { 6 console.log(this.name + " , " + this.gender + " ,今年" + this.age); 7 } 8 } 9 var xh = { 10 name : "小红", 11 gender : "女", 12 age : 18 13 } 14 xw.say(); // "小王 , 男 ,今年24" 15 xw.say.call(xh); // "小红 , 女 ,今年18" 16 xw.say.apply(xh); // "小红 , 女 ,今年18" 17 xw.say.bind(xh)(); // "小红 , 女 ,

浙公网安备 33010602011771号