The ReferenceError will only be thrown if the variable is not defined,
not if the value of the variable is undefined. Let me illustrate:
Example one (given there are no variables defined elsewhere):
if (nowhereDefinedVar) ... // throws an error
Example two:
var someUnintializedVar; // var is now defined and has the initial
value of undefined
// later
if (someUninitialized != null) alert("yay, the variable has a value");
else alert("the var is either null or undefined");
If you want to check, whether another included script has defined some
global variable you should indeed use:
if (window.someVariableMaybeDefinedElsewhere != null) ...
On Tue, Feb 8, 2011 at 8:07 PM, Savageman <[email protected]> wrote:
> I agree with what you say: putting the static methods (which doesn't
> modify the object) are in the namespace than the prototype.
>
> I just made some tests and "discovered" (noticed would be better) than
> the Object behaves a bit differently. They get something in addition
> to the other native types, and the prototype is searched when trying
> to access a non-existent property. http://jsfiddle.net/8DG63/4/
> This doesn't work with other native types (Number, String, etc.) and
> accessing a non-existent property doesn't search through the native's
> prototype to fetch the it.
>
>
> My next question (which is more an observation I can't really explain)
> is about accessing non-existent properties. Reading the typeOf()
> function, I have been reading (item.$family) and this popped in my
> mind:
> - What if the $family property doesn't exists, that can happen, right?
> I've always been screwed by this ReferenceError Exception: "undefined
> variable <name here>".
>
> So I did some tests and observed that no exception is thrown when
> accessing an undefined property. I find this quite inconsistent, but
> that's the language and how it works...
> The real question is: can I solve this annoying thing by checking
> window.myUndefinedVar (or window['myUndefinedVar']) instead of the var
> directly to get rid of this? I'm not wanting to silently avoid this
> undefined exception thing, it could just simplify a lot something like
> this:
>
> if (typeof(myVar) != 'undefined' && myVar != null) could be simplified
> as: if (window.myVar != null). Is it safe?
>
>
> On 8 fév, 13:44, Christoph Pojer <[email protected]> wrote:
>> Those methods are static methods on the native types. Methods on the
>> prototype modify the object they are called from, static methods just act on
>> the passed arguments.
>>
>> In the same way, ' abc '.trim() is a dynamic method while Object.each(obj,
>> fn) is static.