使用cal封裝bind以及封裝promise

bind

   Function.prototype.mybind = function(){
            let that = Array.from(arguments)[0];
            let arr = Array.prototype.slice.call(arguments,1);
            var _this = this;
            return function(){
                    _this.call(that,...arr);
            }
    }

使用

 setTimeout(function(){
        console.log(this);
    }.mybind(document),1000)

Promise


    function MyPromise(cb){
        this.state = "pending";
        this.message="";

        cb((reslove)=>{
            this.state = "resolved";
            this.message = reslove; 
        },(err)=>{
            this.state = "rejected";
            this.message = err;
        })
        return this;
    }
    MyPromise.prototype.then= function(cb){    
                if(this.state==="resolved" || this.state==="rejected"){
                    cb(this.message);  
                }else{
                    return ;
                }
    }

使用:

  new MyPromise((reslove,reject)=>{
        // reject(1);
    }).then((res)=>{
        console.log(11)
    })
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章