欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JS手写call,apply,bind

程序员文章站 2022-07-14 14:28:28
...

1.手写call,apply,bind

//call
Function.prototype.myCall = function(context){
    context = context || window
    context.fn = this
    let arg = [...arguments].slice(1)
    let result = context.fn(...arg)
    delete context.fn
    return result
}
//apply
Function.prototype.myApply = function(context){
    context = context || window
    context.fn = this
    let result
    //这里判断如果有第二个参数,就是一个数组
    if(arguments[1]){
        result = context.fn(...arguments[1])
    }else{
        result = context.fn()
    }
    delete context.fn
    return result
}
// bind
//考虑到原型链,因为在new 一个bind过生成的新函数的时候,必须的条件是要继承原函数的原型
Function.prototype.myBind = function(thisArg){
    if(typeof this !== 'function') return
    let that = this
    let arg = [...arguments].slice(1)
    let fnNop = function(){}
    let fn = function(){
        return that.apply(this instanceof fn ? this : thisArg , arg.concat([...arguments]))
    }
    // 维护原型关系
    if(this.prototype){
        fnNop.prototype = this.prototype
    }
    fn.prototype = new fnNop()
    return fn
}
相关标签: JS核心 javascript