0
点赞
收藏
分享

微信扫一扫

call-apply-bind

洲行 2022-01-26 阅读 40
Function.prototype.myCall = function(ctx){
    if(typeof this !== 'function'){
        throw new TypeError('myCall只能由函数调用')
    }
    ctx = ctx || window
    let args = [...arguments].slice(1)
    let rst = null

    ctx.fn = this
    rst =  ctx.fn(args)
    // 垃圾回收
    delete ctx.fn
    return rst
}

function A(x,y){
    console.log(x+y);
}

function B(x,y){
    console.log(x-y);
}
console.log('----------A.call(B,1,1)-----------');
A.call(B,1,1)

Function.prototype.myApply = function(ctx){
    if(typeof this !== 'function'){
        throw new TypeError('myApply只能由函数调用')
    }
    ctx.fn = this
    let rst = null
    if(arguments[1]){
        rst = ctx.fn(...arguments[1])
    }else{
        rst = ctx.fn()
    }

    delete ctx.fn

    return rst
}
console.log('----------A.apply(B,[1,2])-----------');
A.apply(B,[1,2])


Function.prototype.myBind = function(ctx){
    if(typeof this !== 'function'){
        throw new TypeError('myBind只能由函数调用')
    }

    let args = [...arguments].slice(1)
    let fn = this

    return function Fn(){
        return fn.apply(
            this instanceof Fn ? this : ctx , args.concat(...arguments)
        )
    }
}

console.log('----------A.myBind(B,[1,2])-----------');
A.apply(B,[1,2])
举报

相关推荐

0 条评论