call、apply、bind的用法

來源:互聯網
上載者:User

標籤:hit   int()   object   多次   max   cli   error   拼接   new   

數組追加

      //用apply拼接            var arr1=[12,‘name:foo‘,2048];            var arr2=[‘Joe‘,‘Hello‘];            Array.prototype.push.apply(arr1,arr2);            console.log(arr1);//(5) [12, "name:foo", 2048, "Joe", "Hello"]            //用call拼接            var arr1=[12,‘name:foo‘,2048];            var arr2=[‘Joe‘,‘Hello‘];            Array.prototype.push.call(arr1,arr2);            console.log(arr1);//(4) [12, "name:foo", 2048, Array(2)]  Array(2) ["Joe", "Hello"]是arr2隻佔一位,然後在第三位下面又分2位

擷取數組中的最大值和最小值

      //對比call和apply (參數明確時用call)            var numbers=[25,456,86,-45];            var maxNum=Math.max.apply(Math,numbers)//傳入的是一個數組            console.log(maxNum);//456            var numbers=[25,456,86,-45];            var maxNum=Math.max.call(Math,25,456,86,-45)//傳入的一個個參數            console.log(maxNum);//456

驗證是否是數組(前提是toString()方法沒有被重寫過)

      var arr=[1,2,3,4,5];            function isArray(obj){                 return  Object.prototype.toString.call(obj) === ‘[object Array]‘ ;            }            isArray(arr);            console.log(isArray(arr))//true

apply的用法

       function log(msg)  // 常規寫法            {                console.log(msg);            }            log(1);//1            log(1,2);//1 1

 用apply的方法

       function log()            {                console.log.apply(console,arguments);            }            log(1);//1            log(1,2);//1 2

bind的用法

           //常規寫法
            var foo = { bar : 1, eventBind: function(){ console.log(this) var _this = this; $(‘.someClass‘).on(‘click‘,function(event) { // Act on the event console.log(_this.bar); //1 }); } } foo.eventBind();          
         //bind的寫法
        var foo = { bar : 1, eventBind: function(){ $(‘.someClass‘).on(‘click‘,function(event) { // Act on the event console.log(this.bar); //1 }.bind(this)); } }   foo.eventBind();

bind() 建立了一個函數,當這個click事件綁定在被調用的時候,它的 this 關鍵詞會被設定成被傳入的值(這裡指調用bind()時傳入的參數)。因此,這裡我們傳入想要的上下文 this(其實就是 foo ),到 bind() 函數中。
然後,當回呼函數被執行的時候, this 便指向 foo 對象。

案例

    var bar = function(){                    console.log(this.x);                }            var foo = {                x:3            }            var sed = {                x:4            }            var func = bar.bind(foo).bind(sed);                func(); //3  此時輸出的為3                            var fiv = {                x:5            }            var func = bar.bind(foo).bind(sed).bind(fiv);             func(); //3 //此時輸出的為3

在Javascript中,多次 bind() 是無效的。更深層次的原因,bind() 的實現,相當於使用函數在內部包了一個 call / apply,第二次 bind() 相當於再包住第一次 bind() ,故第二次以後的 bind 是無法生效的。
bind()返回的內容

       var obj = {                    x: 81,                };                            var foo = {                    getX: function() {                        return this.x;                    }            }            var a = foo.getX.bind(obj); //81            console.log(a()); //81//          console.log(foo.getX.bind(obj)()); //81  call和apply是立即執行,而bind返回的是函數

call 方法

            //使用call方法調用匿名函數            var peoples=[                {name:‘Jane‘,age:16},                {name:‘Maria‘,age:15}            ]            for(var i=0;i<peoples.length;i++){                (function(i){                    this.print=function(){                        console.log(i+"----" +this.name+"---"+this.age);                    }                    this.print();                }).call(peoples[i],i)            }
      //使用call方法調用父建構函式            function Product(name,price){                this.name=name;                this.price=price                    if(price < 0){                        throw RangeError(‘Connot create product‘+this.name+‘with a negative price‘);                                    }                }                    function Food(name,price){                    Product.call(this,name,price);                    this.category=‘food‘;                            }                var cheese = new Food(‘feta‘, 5);                console.log(cheese);//Food {name: "feta", price: 5, category: "food"}

簡單用法

          function cat(){                }                cat.prototype={                     food:"fish",                     say:function(){                           alert("I love "+this.food);                     }                }                             var blackCat = new cat;                blackCat.say();                var whiteDog = {food:"bone"};                console.log(whiteDog);                blackCat.say.apply(whiteDog);

總結:

apply 、 call 、bind 三者都是用來改變函數的this對象的指向的;
apply 、 call 、bind 三者第一個參數都是this要指向的對象,也就是想指定的上下文;
apply 、 call 、bind 三者都可以利用後續參數傳參;

apply 、 call 會立刻執行,而bind的回呼函數

apply傳入的是數組apply(this,[argu1,argu2,argu3,argu4]),call是call(this,argu1,argu2,argu3,argu4),如果傳入的參數個數是已知的,可以用call方法。如果個數未知,用apply方法。


 

call、apply、bind的用法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.