Javascript命名禁区
04月 1st, 2011大家都知道的,当我们使用Javascript保留字作为标识符时,会引起程序报错。
大家不一定知道的,当我们使用top, fullScreen, screen等作为标识符时,也会引起程序报错或者执行异常。
报错还好,怕的就是没有报错,而当项目上线后,在某些特定环境下,它才执行异常,这时候来查错才真的要人老命。所以,我们不能留下任何黑洞,我们必须清楚,浏览器端的Javascript到底有哪些命名禁区。
1、input元素上扩展start方法。
在做一个动画框架时,为了方便链式调用,我给元素扩展了一个start的方法,并且测试通过,以为万无一失,这个方法名没被占用,直到碰到这样一段代码:
- var btn = lib.getElem('input'); // 获取到一个input元素
- btn = lib.extend(btn); // 扩展方法
- btn.start();
在IE下报错了,原因是:
input元素已经有了start这样一个属性( input.start 设置或获取视频剪辑文件应该开始播放的时间。 )
2、定义一个fullScreen的全局变量。
- var fullScreen = function(){
- ....//突出显示页面中某一块内容
- }
- alert(fullScreen); // ff中为false
两次的教训,我觉得有必要整理一份Javascript命名禁区表了,不可能完全记住,但至少有一个大体印象。
一、标识符允许的字符集。
在ECMAScript V3中,标识符除首字母外,允许使用除 (./=?:&#\{}()<>[]|~!’”\*^) 等特殊字符外所有的unicode字符集。
二、变量名、函数名、循环标记命名禁区。
1、保留字
break delete function return typeof case do if switch var catch else in this void continue false instanceof throw while debugger finally new true with default for null try
2、未来保留字
abstract double goto native static boolean enum implements package super byte export import private synchronized char extends int protected throws class final interface public transient const float long short volatile
3、扩展列表
as is namespace use arguments encodeURI Infinity Object String Array Error isFinite parseFloat SyntaxError Boolean escape isNaN parseInt TypeError Date eval Math RangeError undefined decodeURI EvalError NaN ReferenceError unescape decodeURIComponent Function Number RegExp URIError
status onresize onmessage parent onhashchange defaultStatus name history maxConnectionsPerServer opener location screenLeft document onbeforeprint screenTop clientInformation onerror onfocus event onload onblur window closed screen onscroll length frameElement self onunload onafterprint navigator frames sessionStorage top clipboardData external onhelp offscreenBuffering localStorage onbeforeunload
5、FF全局变量
getInterface addEventListener loadFirebugConsole console window cehomepage document netscape XPCSafeJSObjectWrapper XPCNativeWrapper Components sessionStorage globalStorage getComputedStyle dispatchEvent removeEventListener name parent top dump getSelection scrollByLines scrollbars scrollX scrollY scrollTo scrollBy scrollByPages sizeToContent setTimeout setInterval clearTimeout clearInterval setResizable captureEvents releaseEvents routeEvent enableExternalCapture disableExternalCapture open openDialog frames applicationCache self navigator screen history content menubar toolbar locationbar personalbar statusbar directories closed crypto pkcs11 controllers opener status defaultStatus location innerWidth innerHeight outerWidth outerHeight screenX screenY mozInnerScreenX mozInnerScreenY pageXOffset pageYOffset scrollMaxX scrollMaxY length fullScreen alert confirm prompt focus blur back forward home stop print moveTo moveBy resizeTo resizeBy scroll close updateCommands find atob btoa frameElement showModalDialog postMessage localStorage
这是最容易被忽视的部分,有的变量允许你重新设置,但最好不要随意去占用它,除非你非常清楚你在干什么,及可能造成的后果
三、属性方法命名禁区。
1、保留字
break delete function return typeof case do if switch var catch else in this void continue false instanceof throw while debugger finally new true with default for null try
2、未来保留字
super export import extends const class
- var testObj = {class: 3}; //ie将报错
- var testObj = {}; testObj['class'] = 3 //则不会



