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

1、圖解call、apply、bind的異同git

JavaScript中函數能夠經過3種方法改變本身的this指向,它們是call、apply、bind。它們3個很是類似,可是也有區別。下面表格能夠很直觀看出三者的不一樣github

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

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

第二個參數以後都是實參app

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

apply

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

第二個參數必須是數組函數

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

bind

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

第二個參數以後都是實參
prototype

var newFunction = function.bind(context);

newFunction(arg1,arg2,arg3...)

2、實例:

一、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實參。

二、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,第二個參數是一個數組

三、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);//函數此時才執行

 3、經常使用場景

一、數組之間追加

    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

二、獲取數組中的最大值和最小值

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

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

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

四、類(僞)數組使用數組方法

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

五、數字求和

    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

相關文章
相關標籤/搜索