AW: [thelist] javascript detecting if function/var is already defined

liorean liorean at f2o.org
Fri Nov 28 05:35:23 CST 2003


christof.hoeke at e-7.com wrote:
> i found a solution myself, sorry for the post...
> 	var x //seems to put x in the current "namespace" without overwriting the current value
> 	if (x == undefined)
> 		//do something other, maybe calling function y but not x
> 	else 
> 		//do something with x, e.g. call it

Just a test:

var x = 'x';
(function(){
     var
         x;
     return [x,
         x == undefined,
         typeof x];
})(); // => [ , true, 'undefined' ]

Nope, that does not seem to work. The reason? Have a look at the 
following list:
1. Determine if member exists on an object:
//(it may exists but be undefined)
   'x' in oParent // => boolean
2. Check what type the variable is:
   typeof x // => string:
// 'undefined'|'object'|'number'|'boolean'|'function'|'string'
// ('undefined' is the result if the variable is not defined,
// independently of whether it exists or not)
3. Determine if the variable is undefined
// (assumes the existense of the variable in the first place)
   x != undefined // => boolean
4. Determine if variable autocasts to true, variants
   Boolean(x) // => boolean
   !x // => boolean (inverted)
   x || false // => anything (but false if it autocasts to false)
-- 
liorean <mailto:liorean at user.bip.net>

ViewStyles, ViewScripts, ToggleStyles and GraphicsInfo bookmarklets and 
Theme Switcher, Cookies Handler scripts:
<http://liorean.web-graphics.com/>



More information about the thelist mailing list