圖解call、apply、bind的異同及各種實戰應用示範

來源:互聯網
上載者:User

標籤:

一、圖解call、apply、bind的異同

JavaScript中函數可以通過3種方法改變自己的this指向,它們是call、apply、bind。它們3個非常相似,但是也有區別。下面表格可以很直觀看出三者的不同

方法 是否直接執行函數 傳入的參數 調用方式
call

(context,arg1,arg2,arg3...)

第二個參數之後都是實參

function.call(context,arg1,arg2,arg3...)

apply

(context,[arg1,arg2,arg3...])

第二個參數必須是數組

function.apply(context,[arg1,arg2,arg3...])

bind

(context)

只有一個參數

var newFunction = function.bind(context);

newFunction(arg1,arg2,arg3...)

二、執行個體:

1、call

    var a = {x: 1};    var b = function (y, z) {        console.log(this.x + y + z)    };    b.call(a, 3, 4);//此時b的this(即b執行時的上下文)被改變為a,因此this.x為1,第二個參數之後都是傳給b實參。

2、apply

   var a = {x: 1};    var b = function (arr) {        console.log(this.x + arr[0] + arr[1])    };    b.call(a, [3, 4]);//此時b的this(即b執行時的上下文)被改變為a,第二個參數是一個數組

3、bind

    var a = {x: 1};    var b = function (y, z) {        console.log(this.x + y + z)    };    var newB = b.bind(a);//此時b的this(即b執行時的上下文)被改變為a,由此產生一個新函數,函數不會立即執行。    newB(3, 4);//函數此時才執行

 三、常用情境

1、數組之間追加

    var array1 = [12, "foo", {name: "Joe"}, -2458];    var array2 = ["Doe", 555, 100];    Array.prototype.push.apply(array1, array2);    /* array1 值變為  [12 , "foo" , {name:"Joe"} , -2458 , "Doe" , 555 , 100] */
View Code

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

    var numbers = [5, 458, 120, -215];    var maxInNumbers = Math.max.apply(Math, numbers);  //458
View Code

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

    function isArray(obj){        return Object.prototype.toString.call(obj) === ‘[object Array]‘;    }
View Code

4、類(偽)數組使用數組方法

var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));
View Code

5、數字求和

    function sum() {        var numberSum = Array.prototype.reduce.apply(arguments, [function (prev, next) {            return prev + next;        }]);        console.log(numberSum);    }    sum(1, 2, 3);
View Code

備忘:以上1-4的使用情境來自,有興趣的同學可以前往瞭解更多:https://github.com/chokcoco/apply-call-bind/tree/master

圖解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.