以下是JavaScript容易犯错的几个"陷阱".由本人google+体验+搜集而来.虽然不是什么很高深的技术问题,但注意一下,会使您的编程轻松些.
1. 最后一个逗号
如这段代码,注意最后一个逗号,按语言学角度来说应该是不错的(python的类似数据类型辞典dictionary就允许如此)。IE会报语法错误,但语义不详,你只能用人眼从几千行代码中扫描。
- <script>
- var theObj = {
- city : "ShenZhen",
- state : "ok",
- }
- </script>
<script>
var theObj = {
city : "ShenZhen",
state : "ok",
}
</script>
2. this的引用会改变
如这段代码:
- <input type="button" value="Gotcha!" id="MyButton" >
- <script>
- var MyObject = function () {
- this.alertMessage = "Javascript rules";
- this.ClickHandler = function() {
- alert(this.alertMessage );
- }
- }();
- document.getElementById("theText").onclick = MyObject.ClickHandler;
- </script>
<input type="button" value="Gotcha!" id="MyButton" >
<script>
var MyObject = function () {
this.alertMessage = "Javascript rules";
this.ClickHandler = function() {
alert(this.alertMessage ); //行1
}
}();
document.getElementById("theText").onclick = MyObject.ClickHandler;
</script>
并不如你所愿,答案并不是”JavaScript rules”。在执行MyObject.ClickHandler时,在行1中,this的引用实际上指向的是document.getElementById("theText")的引用。可以这么解决:
- <input type="button" value="Gotcha!" id="theText" >
- <script>
- var MyObject = function () {
- var self = this;
- this.alertMessage = “Javascript rules”;
- this.OnClick = function() {
- alert(self.value);
- }
- }();
- document.getElementById(”theText”).onclick = MyObject.OnClick
- </script>
<input type="button" value="Gotcha!" id="theText" >
<script>
var MyObject = function () {
var self = this;
this.alertMessage = “Javascript rules”;
this.OnClick = function() {
alert(self.value);
}
}();
document.getElementById(”theText”).onclick = MyObject.OnClick
</script>
实质上,这就是JavaScript作用域的问题。如果你看过,你会发现解决方案不止一种。
3. 标识盗贼
在JavaScript中不要直接使用跟HTML的id一样的变量名。如下代码:
- <input type="button" id="TheButton">
- <script>
- TheButton = document.getElementById("TheButton");
- </script>
<input type="button" id="TheButton">
<script>
TheButton = document.getElementById("TheButton");
</script>