Calling .bind(this, this)?

Hi everyone,

This codewars problem asks you to add a Function method which wraps a function to extend it.

The usage example is

function speak(name){
   return "Hello " + name;
}

speak = speak.wrap(function(original, yourName, myName){
   greeting = original(yourName);
   return greeting + ", my name is " + myName;
})

var greeting = speak("Mary", "Kate"); // 'Hello Mary, my name is Kate'

My solution used call and the arguments object, and was quite long and convoluted.

Then the best answer was simply

Function.prototype.wrap = function(callback) {
  return callback.bind(this, this);
}

Which after much puzzling I can’t quite figure out.

Am I right in thinking that this will then bind the callback to whichever function wrap is called on, and then passes that same function in as the first argument?

What then happens to the rest of the arguments, i.e. per the example above, Mary and Kate?

Thanks for any help!

Yup!

When speak is called with the name arguments, the wrap method has already bound the original function as the first parameter. wrap returns a function that is expecting two more arguments.

It may help to load this code into your browser’s console and try it out. Copypaste the prototype function in first, and then your usage example. Try running console.log on speak before and after being wrapped.

1 Like

Ok thanks for clearing that up for me!