mercredi 22 avril 2015

Can somebody help me write and understand this callback?

I'm trying to write a function utilizing callback that will mimic this behavior:

var fullName = function (firstName, lastName) {
  return firstName + ' ' + lastName;
};

var michaelName = partial(fullName, 'Michael');
michaelName('Moore'); // 'Michael Moore'
michaelName('Jackson'); // 'Michael Jackson'

I was stuck for a while trying to write a function named partial that will call back the function fullName but finally got it to work but am not sure if it's a) correct and b) exactly what is happening.

var partial = function(callback, firstName) {
    var innerFunction = function(lastName) { //I declared an inner function in order to create a closure of the variable lastName
      return callback(firstName, lastName); //The closure is completed (or is it only then created?) by returning the function argument named callback taking firstName and lastName as arguments
    };
    return innerFunction; //the function partial will finally return the closure, function innerFunction
}

var michaelName = partial(fullName, 'Michael');
console.log(michaelName('Moore')); //Michael Moore

Is what I've written in defining the function partial the general pattern for writing a callback? If not, can someone show/point me to where I can study this pattern? Is there any other way to refactor this callback so that it's cleaner? I wasn't sure if I needed to create a new innerFunction but when I did I finally got the behavior to work as intended. Is my reasoning in the comments to the code accurate? Would somebody mind stepping through my code and further explaining what is happening, why callback is returned from innerFunction and why partial returns innerFunction instead of callback? Much obliged.

Aucun commentaire:

Enregistrer un commentaire