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

后端 未结 22 2301
醉话见心
醉话见心 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:22

    call() :-- Here we pass the function arguments individually, not in an array format

    var obj = {name: "Raushan"};
    
    var greeting = function(a,b,c) {
        return "Welcome "+ this.name + " to "+ a + " " + b + " in " + c;
    };
    
    console.log(greeting.call(obj, "USA", "INDIA", "ASIA"));
    

    apply() :-- Here we pass the function arguments in an array format

    var obj = {name: "Raushan"};
    
    var cal = function(a,b,c) {
        return this.name +" you got " + a+b+c;
    };
    
    var arr =[1,2,3];  // array format for function arguments
    console.log(cal.apply(obj, arr)); 
    

    bind() :--

           var obj = {name: "Raushan"};
    
           var cal = function(a,b,c) {
                return this.name +" you got " + a+b+c;
           };
    
           var calc = cal.bind(obj);
           console.log(calc(2,3,4));
    

提交回复
热议问题