call / apply / bind 的區(qū)別 應(yīng)用及apply實(shí)現(xiàn)原理

上一篇:關(guān)于this指向的問(wèn)題
然而call \ apply \ bind一般也是常用來(lái)指定this的指向的


  • 先來(lái)看一下call apply bind的區(qū)別

    call([thisObj[,arg1[, arg2[, [,.argN]]]]]):,提供thisObj改變this指向,不傳將指向globlal. arg1 … argN為被調(diào)用方法的傳參依次傳入

        function hello(name,age){
           console.log(name);
          console.log(age);
        }
        hello.call(this,"tsrot",24);
    

    apply([thisObj,[arg1,arg2,...]]):,提供thisObj改變this指向,不傳將指向globlal. arg1 … argN為被調(diào)用方法的傳參一次傳入

        function hello(name,age){
           console.log(name);
          console.log(age);
        }
        hello.call(this,["tsrot",24]);
    

    bind([thisObj[,arg1[, arg2[, [,.argN]]]]]):,thisObj如果未傳,那么 Global 對(duì)象被用作 thisObj。arg1 … argN可傳可不傳。如果不傳,可以在調(diào)用的時(shí)候再傳。如果傳了,調(diào)用的時(shí)候則可以不傳,調(diào)用的時(shí)候如果你還是傳了,則不生效

     var person = {
        name:"tsrot",
        age:24,
        sayHello:function(age){
            console.log(this.name);
            console.log(age);
        }
     };
      var son = {
       name:"xieliqun"
       };
      //arg1 … argN不傳,在調(diào)用的時(shí)候再傳
      var boundFunc = person.sayHello.bind(son);
      boundFunc(25);
      //直接傳入arg1 … argN,調(diào)用的時(shí)候則可以不傳
      var boundFunc = person.sayHello.bind(son,25);
      boundFunc(); 
    //如果在bind()中直接傳入,調(diào)用的時(shí)候也傳了,則不生效
    

    總結(jié):

    1. call參數(shù)依次傳入,apply參數(shù)一個(gè)數(shù)組直接傳入.bind參數(shù)可傳(調(diào)用時(shí)不用傳),可不傳(調(diào)用時(shí)再傳)
    2. call和apply直接執(zhí)行函數(shù),而bind需要再一次調(diào)用
  • call apply bind 應(yīng)用 (應(yīng)用場(chǎng)景)

    • call

      • call繼承
        function Animal(name) {
                this.name = name;
                this.showName = function () {
                console.log(this.name);//Black Cat
              }
         }
        function Cat(name) {
            Animal.call(this, name); 
        }
        var cat = new Cat('Black Cat');
        cat.showName(); 
        
      • call將偽數(shù)組轉(zhuǎn)化為數(shù)組
          var fakeArr = {0:'a',1:'b',length:2};
        // var arr1 = [].slice.call(fakeArr);
         var arr1 = Array.prototype.slice.call(fakeArr);
         console.log(arr1[0]); //a
         //var arr2 = Array.prototype.slice.call(fakeArr);
           var arr2 = [].slice.call(fakeArr);
         console.log(arr2[0]); //a
           arr1.push("c");
         console.log(arr1); //["a", "b", "c"]
        
    • apply
      • 數(shù)組追加
          var array1 = [1 , 2 , 3, 5];
          var array2 = ["xie" , "li" , "qun" , "tsrot"];
             //[].push.apply(array1, array2);
          Array.prototype.push.apply(array1, array2);
          console.log(array1);//[1, 2, 3, 5, "xie", "li", "qun", "tsrot"]
        
      • 獲取數(shù)組中的最大值和最小值
           var num = [1,3,5,7,2,-10,11];
            var maxNum = Math.max.apply(Math, num);
              var minNum = Math.min.apply(Math, num);
            console.log(maxNum); //11
            console.log(minNum); //-10
        
    • bind 保存this變量
      var foo = {
          bar : 1,
          eventBind: function(){
              var _this = this ;
              $('.someClass').on('click',function(event) {
                  console.log(_this.bar);     
              });
          }
      }
      var foo = {
          bar : 1,
          eventBind: function(){
              $('.someClass').on('click',function(event) {
                  console.log(this.bar);      
              }.bind(this));
          }
      }
      
  • apply實(shí)現(xiàn)原理

    •  //原生封裝
       Function.prototype.myBind = function () {
           let obj = arguments[0];
           let arg = [].slice.call(arguments, 1);
           let that = this;
           return function () {
               let arg1=[].slice.call(arguments);
               that.apply(obj, arg.concat(arg))
           }
       };
       //ES6封裝
           Function.prototype.myBind = function (content, ...arg) {
               let _this = this;
               return function (...arg1) {
                   _this.apply(content, [...arg, ...arg1]);
               }
           }
           let f = fn.myBind([], 1, 2, 3);
           f()
      

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容