最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What does it mean to pass `undefined` to bind()? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Jan 17, 2013 at 15:41 BeeBandBeeBand 11.5k19 gold badges65 silver badges84 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 17

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.

The first parameter to bind specifies the this value inside the function. It can be used to convert it to a 'method' that acts on an object. However if you pass undefined it means it remains a function. So in the example you mentioned above there is no difference.

发布评论

评论列表(0)

  1. 暂无评论