js中test做全局变量
今天想测试一下dom中的空格来着,却发现了一个很隐秘的东西。ie中不能让test作为全局变量。最初的测试代码如下:
js代码:
<script type="text/javascript">
window.onload = function(){
test = document.getElementById('test');
test.style.backgroundColor = "red";
}
</script> html代码:
<body>
<h1>DOM简介</h1>
<p id="test">dom的广泛使用是有道理的,以下是一些原因:</p>
</body> 然后在firefox中测试,发现文本“dom的广泛使用是有道理的,以下是一些原因:”出现了红色。即显示了样式。然而在ie7和ie6下测试则都没有效果。
于是,将test设为局部变量,即将“test=document.getElementById('test')”改为“var test=getElementById('test')”。就能在ie下看到红色文本的效果了。然后我又在将原来的test换成其它变量名,并且还是全局变量。还是能看到效果。翻了翻犀牛书,发现test不是javascript的关键字或保留字,这就肯定了test不能作为ie全局变量名这一结论。所以以后在写js的时候还要好好注意变量的命名。这里就先把js关键字和保留字列出来。o(∩_∩)o...
以下内容来自《javascript权威指南第五版》
Reserved JavaScript keywords
| break | if | do | switch | typeof |
| case | else | in | this | var |
| catch | false | instanceof | tHRow | void |
| continue | finally | new | true | while |
| default | for | null | try | with |
| delete | function | return |
Words reserved for ECMA extensions
| 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 |
| debugger |
Other identifiers to avoid
| arguments | encodeURL | Infinite | Object | String |
| Array | Error | isFinite | praseFloat | syntaxError |
| Boolean | escape | isNaN | parseInt | typeError |
| Date | eval | Math | RangError | undefined |
| decodeURL | EvalError | NaN | ReferenceError | unescape |
| decodeURLComponent | Function | Number | RegExp | URLError |
window.onload 
浙公网安备 33010602011771号