面试题js之 bind、call、apply
bind、call、apply
共同点:都是改变this的指向
区别
bind | call | apply |
---|---|---|
第一个参数是this要指向的对象,多个参数 类型不限 | 第一个参数是this要指向的对象,多个参数 类型不限 | 第一个参数是this要指向的对象,第二个参数是数组 |
bind()改过this后,不执行函数,会返回一个绑定新this的函数 | call()改过this的指向后,会再执行函数 | 改过this的指向后,会再执行函数 |
实际用法:
bind
//react 的 constructor中 改变指定的事件的this指向
class App extends React.Component {
constructor(props){
super(props);
this.clickHande = this.clickHande.bind(this);
}
clickHande(){
//....
}
}
call
//利用call()判断数据类型
//在判断数据类形式使用typeof,一般不是太准确的,我们可以使用Object.prototype.toString.call()方法来判断一个数据的数据类型
console.log(Object.prototype.toString.call("qq")) // [Object String] 返回值都是字符串类型****
apply
利用apply()求最大值
var arr =[2,6,8,3,4,9,7,23,56,889]
console.log(Math.max.apply(arr,arr))
//apply()所执行的操作:1.执行Math.max(1,2,3,5,4) 2.把内部的this改成arr
参考:https://blog.csdn.net/wyyandyou_6/article/details/81488103