封装call,apply,bind

2019-10-26  本文已影响0人  那麽快樂
<script>
    let obj={
        name:'qwe',
        fn(){
            console.log(this.name)
            console.log(...arguments)
        }
    }
    let obj2={
        name:'zxc'
    }
    //封装call
    Function.prototype.myCall=function(that,...argu){
            that=that||window
        var fnName=Symbol(this.name)

        that[fnName]=this;

        let res=that[fnName](...argu);
        delete that[fnName]
    }
    // obj.fn.myCall(obj2,1,2,3)
    //apply
    Function.prototype.myApply=function(that,argu){
        that=that||window
        fnName=Symbol(this.name)
        that[fnName]=this
        that[fnName](...argu)
        delete that[fnName]
    }
    // obj.fn.myApply(obj2,[1,2,3])
  //bind
    Function.prototype.myBind=function(that,...argu){
        that=that||window
        let _self=this
        return function(){
            _self.myApply(that,argu.concat(...arguments))
        }
    }
    let fn2=obj.fn.myBind(obj2,1,4,5)
    fn2()
    </script>
上一篇下一篇

猜你喜欢

热点阅读