typeof !== "undefined" vs. != null
I often see JavaScript code which checks for undefined parameters etc. this way:
if (typeof input !== "undefined") {
// do stuff
}
This seems kind of wasteful, since it involves both a type lookup and a string comparison, not to mention its verbosity. It's needed because 'undefined' could be renamed, though. My question is: How is that code any better than this approach:
if (null != input) {
// do stuff
}
As far as I know, you can't redefine null, so it's not going to break unexpectedly. And, because of the type-coercion of the != operator, this checks for both undefined and null... which is often exactly what you want (eg for optional function parameters). Yet this form does not seem widespread, and it even causes JSLint to yell at you for using the evil != operator. Why is this considered bad style?
typeof
allows the identifier to never have been declared before. So it's safer in that regard:
if(typeof neverDeclared == "undefined") //no errors
if(neverDeclared == null) //throws ReferenceError: neverDeclared is not defined
If the variable is declared (either with the var
keyword, as a function argument, or as a global variable), I think the best way to do it is:
if (my_variable === undefined)
jQuery does it, so it's good enough for me :-)
Otherwise, you'll have to use typeof
to avoid a ReferenceError
.
If you expect undefined to be redefined, you could wrap your code like this:
(function(undefined){
// undefined is now what it's supposed to be
})();
good way:
if(typeof neverDeclared == "undefined") //no errors
But the best looking way is to check via :
if(typeof neverDeclared === typeof undefined) //also no errors and no strings
链接地址: http://www.djcxy.com/p/55866.html
上一篇: Ajax正在返回空字符串