博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

javascript 手动实现 bind,call,apply

Posted on 2023-11-08 10:04  绝交  阅读(12)  评论(0编辑  收藏  举报

 

js 手动实现call方法

    Function.prototype.myCall=function(content,...args){
        let myfn = Symbol()
        content = content|| globalThis
        // console.log(content)
        content[myfn] = this
        // console.log(content)
        const result = content[myfn](...args)
        delete content[myfn]
        // console.log(content)
        return result
    }


    function myFn(a,b){
        console.log(this.name,a,b)
        return 1
    }
    console.log(myFn.myCall({name:'zhang'},3,4))

 

js 手动实现apply方法

 

Function.prototype.myApply = function(myThis,args){
        myThis = myThis || globalThis;
        args = args || []
        const fnName = Symbol()
        myThis[fnName] = this
        const result = myThis[fnName](...args)
        delete myThis[fnName]
        return result
    }

    function myFn(a,b){
        console.log(this.name,a,b)
        return 1
    }
    console.log(myFn.myApply({name:'zhang'},[3,4]))

 

js 手动实现bind方法

Function.prototype.myBind = function(myThis,...args1){

        const myfn = this
        return function(...args2){
            const result = myfn.apply(myThis,[...args1,...args2])
            console.log(myfn,myThis)
            return result;
        }
    }

    function myFn(...args){
        console.log(this.name,args)
        return 1
    }
    let a = myFn.myBind({name:'zhang'},3,4)
    console.log(a(5,6))
    console.log(a(5,6,7,8,9))

    let b = myFn.myBind({name:'zhang'},3,4)
    console.log(b(5,6))
    console.log(b(5,6,7,8,9))