Javascript call() & apply() vs bind()?

后端 未结 22 1954
醉话见心
醉话见心 2020-11-22 02:42

I already know that apply and call are similar functions which setthis (context of a function).

The difference is with the way

22条回答
  •  失恋的感觉
    2020-11-22 03:34

    Assume we have multiplication function

    function multiplication(a,b){
    console.log(a*b);
    }
    

    Lets create some standard functions using bind

    var multiby2 = multiplication.bind(this,2);

    Now multiby2(b) is equal to multiplication(2,b);

    multiby2(3); //6
    multiby2(4); //8
    

    What if I pass both the parameters in bind

    var getSixAlways = multiplication.bind(this,3,2);
    

    Now getSixAlways() is equal to multiplication(3,2);

    getSixAlways();//6
    

    even passing parameter returns 6; getSixAlways(12); //6

    var magicMultiplication = multiplication.bind(this);
    

    This create a new multiplication function and assigns it to magicMultiplication.

    Oh no, we are hiding the multiplication functionality into magicMultiplication.

    calling magicMultiplication returns a blank function b()

    on execution it works fine magicMultiplication(6,5); //30

    How about call and apply?

    magicMultiplication.call(this,3,2); //6

    magicMultiplication.apply(this,[5,2]); //10

    In simple words, bind creates the function, call and apply executes the function whereas apply expects the parameters in array

提交回复
热议问题