说说call-apply-bind的作用及区别
# 是什么
作用:改变函数执行的上下文, 简单的说就是更改函数执行的this指向
# 怎么用
# call
第一个参数为null, undefined时, this指向window
let arr = [1,2,3,4]
Math.max.call({}, ...arr)
# apply
let arr = [1,2,3,4]
Math.max.apply({}, arr)
# bind
function fn(...args){
console.log(this, args)
}
let obj = {
name: 'fang'
}
let bindFn = fn.bind(obj)
bindFn(1,2) // obj, 1, 2
fn(1,2) // window ,1, 2
# 原理
- call
Function.prototype.myCall = function(context){
context.fn = this
let args = [...arguments].slice(1)
let result = context.fn(...args)
delete context.fn
return result
}
let arr = [1,2,3,4]
Math.max.myCall({}, ...arr)
- apply
Function.prototype.myApply = function(context,arr){
context.fn = this
let args = arr
let result = context.fn(...args)
delete context.fn
return result
}
let arr = [1,2,3,4]
Math.max.myApply({}, arr)
- bind
Function.prototype.myBind = function(context){
let fn = this
let args = [...arguments].slice(1)
// 返回一个函数
return function Fn(){
// 根据类型不同,返回不同
// 有没有想到eventbus中的once
return fn.apply(this instanceof Fn?
new fn(...arguments) :
context, args.concat(...arguments)
)
}
let result = context.fn(...args)
delete context.fn
return result
}
上次更新: 2021/12/19, 18:05:42