0

Can someone please explain why when we use bind instead of apply this does not work correctly.

Lets say I have a simple function:

function addFourNumbers(a,b,c,d){
        return a+b+c+d;
    }

I try to create a function that I could use to call the above function later with the correct value of 'this' and parameters could be passed anytime:

function bind(fn, thisArg){

    var outArg = [].slice.call(arguments, 2);

    return function(){
    var inArg = [].slice.call(arguments);
    var allArg = outArg.concat(inArg);
    return fn.apply(thisArg, allArg);
    }
}

Now when I call the following it works:

var t = bind(addFourNumbers,this,1)
t(2,3,4); //output 10

var t = bind(addFourNumbers,this,1,2)
t(3,4); //output 10

Now I'm confused if I change apply to bind

function bind(fn, thisArg){

    var outArg = [].slice.call(arguments, 2);

    return function(){
    var inArg = [].slice.call(arguments);
    var allArg = outArg.concat(inArg);
    return fn.bind(thisArg, allArg);
    }
}

and try to execute:

var t = bind(addFourNumbers,this,1,2)
t(3,4)(); //output 1,2,3,4undefinedundefinedundefined

Any suggestions why?

Thanks

  • Possible duplicate of [Javascript call() & apply() vs bind()?](https://stackoverflow.com/questions/15455009/javascript-call-apply-vs-bind) – Jorge Fuentes González Apr 18 '18 at 04:43
  • As a programmer tip. Ask the question to Google or just read documentation about Apply and Bind. You will get your reply faster. Remeber that before asking here, you have to do your research before, to avoid wasting everyone time. – Jorge Fuentes González Apr 18 '18 at 04:44

0 Answers0