实现this指向的bind、call、apply方法

73 阅读1分钟
实现this指向的bind、call、apply方法
  1. 修改this指向有bind、call、apply三种方法,模仿它们的实现

bind、call、apply区别 

  1. bind 应用场景(一切不需要立即执行的情况,如,点击事件触发某个函数执行,需要改变函数内this指向的),只是绑定不立即执行。
  2. call、apply都是立即执行函数,传参有点区别。
//自定义bind
Function.prototype.mybind = function (){
    // let args = Array.prototype.slice.call(arguments)
    // let args = [...arguments]
    let args = Array.from(arguments)
    let _this = args.shift()|| window
    let self = this
    return function (){
        self.apply(_this,args)
    }
}
Function.prototype.mycall = function (){
    let args = [...arguments]
    let _self = args.shift()|| window
    let fn = Symbol('fn')
    _self[fn] = this
    let result = _self[fn](...args)
    delete _self[fn]
    return result //如果方法有返回
}

Function.prototype.myapply = function (){
    let args = Array.from(arguments)
    let _self = args.shift() || window
    let fn = Symbol('fn')
    _self[fn] = this
    let array = args.length ? args[0] : []
    let ruselt = _self[fn](...array)
    delete _self[fn]
    return ruselt
}