手写apply、bind、call函数的实现

2,058 阅读1分钟

20210414155100.png

    apply、call、bind是挂载在Function对象上的三个方法,调用这三个方法必须是一个函数。
  • 在浏览器里,全局范围内的this指向window
  • 在函数内,this永远指向最后调用他的那个对象
  • 在构造函数中,this指向new出来的那个对象
  • call、apply、bind中的this被强制绑定在指向的那个对象上
  • 箭头函数中的this比较特殊,其this指向其父作用域的this

实现一个bind函数

Function.prototype.myBind = function (context) {
     // 不是函数抛出异常
    if (typeof this !== 'function') {
        throw new Error('类型错误')
    }
    let _this = this
    // 保留上个函数的传值
    let args = Array.prototype.slice.call(arguments, 1)
    return function () {
        // args.concat(arguments) 这两个顺序不能变 arguments为类数组没有concat方法
        _this.apply(context, args.concat(arguments))
    }
}

实现一个apply函数

// 实现原理 this永远指向最后调用他的那对象
Function.prototype.myApply = function (context) {
    if (typeof this !== 'function') {
        throw new Error('类型错误')
    }
    let key = Symbol('key')
    context[key] = this
    let result = context[key](Array.prototype.slice.call(arguments, 1))
    delete context[key]
    return result
}

实现一个call函数

Function.prototype.myCall = function (context, ...ags) {
    if (typeof this !== 'function') {
        throw new Error('类型错误')
    }
    let key = Symbol('key')
    context[key] = this
    let reslut = context[key](...ags)
    delete context[key]
    return reslut
}