Domanda

Reading underscore's source, I noticed the use of void 0 instead of undefined. I know in some browsers undefined can be overwritten, and that a solution to this, in many cases, is just omitting an argument when calling a function, or return;-ing. In fact, for minification purposes, it makes much more sense to do this rather than using void 0.

Also, jquery's aproach to this issue:

(function (window, undefined){
  /* ... */
}(window));

seems to be better in every sense. It is much more readable than void 0, can be minified further, and might give some tiny performance boost as explained in the linked answer.

OK, void 0 appears about 6 times in underscore and 9 in backbone, so it doesn't make much of a difference. So, my question is: Is there any reason or corner cases where void 0 is preferable?

È stato utile?

Soluzione

Here's an example of why the "undefined argument" thing can be a horrible idea.

Let's say you get used to doing it. And you start applying it to other functions too, like this:

function doSomething(undefined) {
    // blah blah blah
    if( something == undefined) {
        // problem
    }
}

All good, right?

Let's say that this function is an event handler.

someElement.onclick = doSomething;

Oh dear. doSomething gets passed an Event object, which is most certainly not undefined!

void 0 is much more robust, as it doesn't rely on a quirk or an assumption to work.

Altri suggerimenti

As you said, void 0 means undefined. Since older browsers undefined can be overwritten. void 0 is guaranteed and will always be undefined. But i do not think, there is no much difference between no argument undefined(jquery way) and void 0.

I think, void 0 is just a coding preference.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top