亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Javascript動(dòng)手實(shí)現(xiàn)call,bind,apply的代碼詳解

 更新時(shí)間:2022年02月22日 11:44:11   作者:krysliang  
這篇文章主要為大家詳細(xì)介紹了Javascript動(dòng)手實(shí)現(xiàn)call,bind,apply的代碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助

1.檢查當(dāng)前調(diào)用的是否為函數(shù)

2.如果當(dāng)前沒(méi)有傳入指向的this,則賦值為window

3.將fn指向當(dāng)前調(diào)用的函數(shù)

4.獲取傳入的參數(shù)

5.將參數(shù)傳入fn進(jìn)行調(diào)用

6.將對(duì)象上的fn刪除

7.返回結(jié)果

  //普通call的實(shí)現(xiàn)
  function hello(){
      console.log('hello 我是'+this.name);
  };
  let person = {
      name:'krys'
  };
  var name = 'liang';//只有var的變量屬于window
  hello();// 'hello 我是liang'
  hello.call(person);//'hello 我是krys'
  hello.call();//'hello 我是liang'
  let person2 = {
      name:'lwl'
  }
  Function.prototype.mycall = function(context){
      //不傳入?yún)?shù)的時(shí)候,默認(rèn)為window
      if(typeof this !== "function"){
          throw new TypeError('Error');
      }
      context = context || window;
      context.fn = this;//fn就是上面的hello方法
      const args = [...arguments].slice(1);//第一個(gè)參數(shù)不要
      const result = context.fn(...args);//把剩下的其他參數(shù)傳給hello
      delete context.fn;
      return result;
  }
  hello.mycall(person2);
function getParams(){
        console.log('我是',this.name,'獲取一些參數(shù)',...arguments);
    }
    let person3 = {
        name:'hhh'
    };
    getParams.apply(person3,['hello','world'])
    Function.prototype.myApply = function(context){
        if(typeof this !== "function"){
            throw new TypeError()
        }
        context = context || window;
        context.fn = this;
        let result;
        if(arguments[1]){
            //如果有傳入?yún)?shù)數(shù)組
            console.log(arguments[1])
            result  = context.fn(...arguments[1]);
        }else{
            result  = context.fn();
        }
        delete context.fn;
        return result;
    }
    getParams.myApply({name:'llll'},['jjj','kkkk','llll']);
function getParams(){
        console.log('我是',this.name,'獲取一些參數(shù)',...arguments);
    }
    let person3 = {
        name:'hhh'
    };
    let person4 = {
        name:'tttt'
    };
    getParams.bind(person3,'hello','world')
    getParams.bind(person4,'hello','world')('jjj','kkk');
    Function.prototype.myBind = function(context){
        if(typeof this !== "function"){
            throw new TypeError()
        }
        context = context || window;
        const _that = this;
        const args = [...arguments].slice(1);
        return function F(){
            if(this instanceof F){
                return new _that(...args,...arguments);//這里的arguments是上面的jjj kkk
            }
            return _that.apply(context,args.concat(...arguments));//這里的arguments是上面的jjj kkk
        }
    }
    getParams.myBind({name:'llll'},'jjj','kkkk','llll')('hhhhllll');

總結(jié)

本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!  

相關(guān)文章

最新評(píng)論