call、apply、bind用法及不同点
- 相同点:
1. call、apply、bind都是Function原型上的方法,所有的函数都可以调用这三个方法
2. call、apply、bind都能将调用该方法的函数中的this指向该方法的第一个参数
3. call、apply方法能在改变this指向的同时,执行调用者函数
- 不同点
1. call、apply会调用函数,而bind不会,bind会返回一个和调用者函数一样的函数
2. call和bind会将第二个及后面的所有参数传递进调用者函数内,而apply的第二个参数为数组,调用apply时,会先将该数组展开,然后传入调用者函数
Function.prototype.myCall = function(o,...rest){
if(o===null||o===undefined){
o = window
}
if(typeof o !== 'function' && typeof o !== 'object'){
o = Object(o)
}
const msg = Symbol('msg')
o[msg] = this
const res = o[msg](...rest)
delete o[msg]
return res
}
apply方法和call类似,因为apply第二个参数为一个数组,则形参不需要用...rest接收,直接定义一个形参接收数组即可
Function.prototype.myBind = function(){
const _this = this
const args = Array.from(arguments)
return function(){
return _this.apply(args[0],args.slice(1))
}
}
欢迎补充^ ^