基础必会必知之手写call、apply、bind方法

call实现总结:

  1. 将函数设为对象的属性
  2. 执行&删除这个函数
  3. 指定 this到函数并传入给定参数执行函数
  4. 如果不传入参数,默认指向为 window
    ### call实现
    Function.prototype.myCall = function (context = window) {
        context.fn = this // 保存函数调用者
        let args = [...arguments].slice(1) // 截取参数
        let result = context.fn(...args) // 执行函数,得到执行结果
        delete context.fn // 用完删除
        return result // 返回执行结果
    } 
    let obj = {
        age: 18
    }
    
    let age = 23
    function bar () {
        console.log(sex,name,this.age)
    }
    bar.myCall(obj,'男', 'czk') // 男 czk 18
复制代码

apply: 与call一致,只有执行方法时传参格式不同

    ### apply实现
    Function.prototype.myApply = function (context = window) {
        context.fn = this
        let args = [...argments].slice(1)
        let result = context.fn(args)
        return result
    }
复制代码

bind的实现:

  1. 首先要明白bind函数会创建一个新的函数 当新函数被调用的时候 bind()的第一个参数将作为它运行时的this
  2. 之后的一系列参数将在传递的实参前作为它的参数
  3. bind在调用时会返回一个和之前函数体一猫一样的函数 只是this的指向发生了改变 bind调用时传的参数会同样传给返回的函数
    ### bind实现
    Function.prototype.myBind = function(context = window) {
        let that = this
        let args = [...arguments].slice(1)
        return function () {
            that.apply(context, args.concat([...arguments]))
        }
    }
    
    let obj = {
      value : 99
    }

    function bar (name , age) {
      console.log(name, age, this.value)
    }

    let getBar = bar.myBind(obj, 'czk')
    getBar('smile') // czk smile 99
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享