Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I always thought I could just check an undefined var by comparing it to undefined, but this is the error I get in the chrome console :

enter image description here

How how do i check for the object jQuery being undefined ?

EDIT :

enter image description here

if(jQuery) is giving me problems too

EDIT :

solution :

if(window.jQuery) works. typeof(jQuery) == 'undefined' works too.

Could anyone explain why ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
126 views
Welcome To Ask or Share your Answers For Others

1 Answer

There are several solutions:

  1. Use typeof. It is a special operator and will never result in a ReferenceError. It evaluates to "undefined" for, well, the undefined value or for a variable which does not exist in context. I'm not a fan of it, but it seems very common.

  2. Use window.jQuery. This forces a "property lookup": property lookups never fail, and return undefined if said property does not exist. I've seen it used in some frameworks. Has the downside of assuming a context (usually window).

  3. Make sure the variable is "declared": var jQuery; if (jQuery) { /* yay */ }. Doesn't seem very common, but it is entirely valid. Note that var is just an annotation and is hoisted. In the global context this will create the "jQuery" property.

  4. Catch the ReferenceError. Honestly, I have never seen this nor do I recommend it, but it would work.

Happy coding.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...