JavaScript的9个陷阱及评点
作者:Realazy 来源:Realazy 时间:2007-08-28 15:10:00
来自 Nine Javascript Gotchas , 以下是JavaScript容易犯错的九个陷阱。虽然不是什么很高深的技术问题,但注意一下,会使您的编程轻松些,即所谓make life easier. 笔者对某些陷阱会混杂一些评点。
1. 最后一个逗号
如这段代码,注意最后一个逗号,按语言学角度来说应该是不错的(python的类似数据类型辞典dictionary就允许如此)。IE会报语法错误,但语焉不详,你只能用人眼从几千行代码中扫描。
<script>
var theObj = {
city : "Boston",
state : "MA",
}
</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>
并不如你所愿,答案并不是”JavaScript rules”。在执行MyObject.ClickHandler时,代码中红色这行,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>
实质上,这就是JavaScript作用域的问题。如果你看过,你会发现解决方案不止一种。
标签:JavaScript,陷阱
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
浅谈Go语言中字符串和数组
2024-04-25 15:14:36
python计算机视觉opencv图像金字塔轮廓及模板匹配
2021-10-10 09:15:33
![](https://img.aspxhome.com/file/2023/7/105307_0s.png)
Django CBV与FBV原理及实例详解
2023-02-14 20:39:01
![](https://img.aspxhome.com/file/2023/8/93838_0s.png)
浅析mysql迁移到clickhouse的5种方法
2024-01-27 21:51:47
![](https://img.aspxhome.com/file/2023/4/110134_0s.png)
Python自动化操作实现图例绘制
2021-03-07 11:24:40
![](https://img.aspxhome.com/file/2023/1/95211_0s.png)
Pytorch 之修改Tensor部分值方式
2023-04-11 06:45:12
基于Python实现天天酷跑功能
2022-09-30 01:18:33
![](https://img.aspxhome.com/file/2023/3/72843_0s.jpg)
Php中用PDO查询Mysql来避免SQL注入风险的方法
2023-07-18 06:37:42
flask框架jinja2模板与模板继承实例分析
2023-08-26 22:21:34
用ASP打造一个小型的网页BBS系统
2008-10-10 16:36:00
用 Python 写的文档批量翻译工具效果竟然超出想象
2022-02-10 08:38:51
![](https://img.aspxhome.com/file/2023/0/107590_0s.jpg)
在Python中实现字典反转案例
2022-12-17 02:05:46
thinkphp3.x连接mysql数据库的方法(具体操作步骤)
2023-11-22 20:04:41
详解JS深拷贝与浅拷贝
2024-05-22 10:40:40
![](https://img.aspxhome.com/file/2023/0/123400_0s.png)
使用python测试prometheus的实现
2023-08-31 15:24:05
![](https://img.aspxhome.com/file/2023/3/72873_0s.jpg)
MySQL分页优化解析
2008-12-22 14:56:00
在sqlserver2005中安装sql server 2000的示例数据库northwind的方法
2024-01-18 11:00:12
Python中super()的理解以及应用场景实例
2021-09-13 08:16:21
![](https://img.aspxhome.com/file/2023/4/112434_0s.png)
如何防范利用刷新来“作弊”的计数器?
2009-11-22 17:18:00
mysql8.0.21下载安装详细教程
2024-01-26 15:40:00
![](https://img.aspxhome.com/file/2023/2/69242_0s.jpg)