简体   繁体   中英

what's the benefit of binding to `undefined` instead of `null`

I often see that when a function needs to be called with bound parameters in no particular context the undefined is more often than not is preferred over the null as a choice of context, as in:

f.call(undefined, param1, param2)

is preferred over:

f.call(null, param1, param2)

I'm wondering if there is any particular reason for this?

What's the benefit of binding to undefined instead of null ?

I don't think there is any. From 10.4.3 Entering Function Code :

  1. If the function code is strict code , set the ThisBinding to thisArg .
  2. Else if thisArg is null or undefined , set the ThisBinding to the global object.
  3. ...

So, if the code is not strict, in both cases this will be set to the global object.

But if the code is strict, this will actually either be null or undefined . f could be implemented to distinguish these cases, but that doesn't seem to be a very likely scenario to me.

In javascript, undefined extends past the scenario where a value has not been set. For instance, if you are looking for a property on a model that does not exist, it will yield undefined.

Its not that odd either to have code like this:

var k;

//do something (possibly setting k)

alert(k);

If the value has not been set, it will be undefined rather than null.

Long story short, it is still a preference, but by using undefined you are more likely to catch the cases where values have not been initialized or try accessing properties of objects that do no exist.

Not sure this answers your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM