美文网首页
封装call,apply,bind

封装call,apply,bind

作者: 那麽快樂 | 来源:发表于2019-10-26 08:56 被阅读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>

    相关文章

      网友评论

          本文标题:封装call,apply,bind

          本文链接:https://www.haomeiwen.com/subject/feryvctx.html