Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to pass `undefined` to bind()?

I was reading some documentation about the bind() function in javascript.

One of the examples starts off like this:

function list() {
  return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

//  Create a function with a preset leading argument
var leadingZeroList = list.bind(undefined, 37);

var list2 = leadingZeroList(); // [37]

So my question is:

What exactly does it means to pass (undefined, 37) to bind() here?

like image 255
BeeBand Avatar asked Jan 17 '13 15:01

BeeBand


1 Answers

It means that you don't want this to refer to anything in the resulting bound function. In other words, it assures that when you call your bound function, this will be undefined. Exactly why you'd do that of course depends on the code; lots of functions don't use this so it's a way of being tidy.

Note that in non-strict mode, it may be the case that the runtime will substitute the global object (window in a browser) for undefined, but I can find no spec that stipulates that behavior. In strict mode, no such substitution is performed.

like image 57
Pointy Avatar answered Sep 18 '22 16:09

Pointy