javascript中变量没有类型,只有值有类型。变量可以随时持有任何类型的值。
var a = 42; typeof a;//"number" a = true; typeof a;//"boolean" typeof typeof 45;//"string" //变量在未持有值的时候为undefined,即typeof 返回 “undefined”。 var a; typeof a;//"undefined" typeof b;//"undefined" a;//undefined b;//ReferenceError;b is not defined
上面代码中的b为undeclared,没有在作用域中声明过的变量。但是浏览器对他的处理容易让人产生误解,typeof返回“undefined”,值返回is not defined 。这其实因为typeof的一个特殊的安全防范机制。
javascript将undefined和undeclared混为一谈,其实他们是两码事。undefined是值的一种,undeclared表示变量还没有被声明过。但是,有时通过typeof的安全防范机制(阻止报错)来检查全局的undeclared变量也是个不错的办法:
/*DEBUG为全局变量,“调试模式”的开关。在输出调试信息到控制台之前,会检测DEBUG变量是否已被声明 顶层的全局变量声明var DEBUG = true只在debug.js文件中有,只在开发及测试时加载到浏览器 */ if(DEBUG){//抛错 console.log("Debugger is begin"); } if(typeof DEBUG !== "undefined"){//安全 console.log("Debugger is begin"); } //对内建API也有作用 if(typeof atob === "undefined"){ atob = function(){/*contenrt*/}; }此外也可用判断全局变量是否是全局对象的属性检查:
/*DEBUG为全局变量,“调试模式”的开关。在输出调试信息到控制台之前,会检测DEBUG变量是否已被声明 顶层的全局变量声明var DEBUG = true只在debug.js文件中有,只在开发及测试时加载到浏览器 */ //检查全局变量是否是全局对象的属性,浏览器全局对象是window if(window.DEBUG){//安全 console.log("Debugger is begin"); } if(!window.atob){//安全 // .. } //缺点是全局变量也可以使服务端 node.js typeof同时也可用于非全局变量的检查以及另外的变量检查方法供参考: //typeof在非全局变量的应用 function doSomethingCool(){ var helper = (typeof FeatureA !== "undefined") ? FeatureA : function(){/* .. default feature.. */} var val = helper(); } /*其他模块和程序引入doSomethingCool()时。此函数会检测变量FeatureA是否已经在宿主 程序中定义过;是,就用现成的,否则自己定义 */ //一个立即执行函数表达式(LIFE) (function(){ function FeatureA(){/*.. my A feature..*/} //包含doSomethingCool(..) function doSomethingCool(){ var helper = (typeof FeatureA !== "undefined") ? FeatureA : function(){/* .. default feature.. */} var val = helper(); } doSomethingCool(); })(); /*这里FeatureA并不是全局变量,但是还是可以用typeof安全防范机制做检查,因为这里没有全局对象可用 下面是另一种方法:“依赖注入”设计模式 */ function doSomethingCool(FeatureA){ var helper = FeatureA || function(){/*default feature*/} var val = helper(); }