| 订阅 RSS

JavaScript中的”陷阱”

August 16th, 2008 目录:个人

以下是JavaScript容易犯错的几个”陷阱”.由本人google+体验+搜集而来.虽然不是什么很高深的技术问题,但注意一下,会使您的编程轻松些.

1.最后一个逗号

如这段代码,注意最后一个逗号,按语言学角度来说应该是不错的(python的类似数据类型辞典dictionary就允许如此)。IE会报语法错误,但语义不详,你只能用人眼从几千行代码中扫描。

var theObj = {
city : "ShenZhen",
state : "ok",
}

var theObj = {
city : "ShenZhen",
state : "ok"
}

9. this的引用会改变

如这段代码:

var MyObject = function () {
this.alertMessage = "Javascript rules";
this.ClickHandler = function() {
alert(this.alertMessage );
}
}();
document.getElementById("theText").onclick = MyObject.ClickHandler;
var MyObject = function () {
this.alertMessage = "Javascript rules";
this.ClickHandler = function() {
alert(this.alertMessage );
}
}();
document.getElementById("theText").onclick = MyObject.ClickHandler;

并不如你所愿,答案并不是”JavaScript rules”。在执行MyObject.ClickHandler时,在行1中,this的引用实际上指向的是document.getElementById(“theText”)的引用。可以这么解决:


var MyObject = function () {
var self = this;
this.alertMessage = “Javascript rules”;
this.OnClick = function() {
alert(self.value);
}
}();
document.getElementById(”theText”).onclick = MyObject.OnClick

var MyObject = function () {
var self = this;
this.alertMessage = “Javascript rules”;
this.OnClick = function() {
alert(self.value);
}
}();
document.getElementById(”theText”).onclick = MyObject.OnClick

实质上,这就是JavaScript作用域的问题。如果你看过,你会发现解决方案不止一种。

2. 标识盗贼

在JavaScript中不要直接使用跟HTML的id一样的变量名。如下代码:


TheButton = document.getElementById("TheButton");

TheButton = document.getElementById("TheButton");

IE会报对象未定义的错误。我只能说:IE 真烂.
若在TheButton之前加上var 声明,或者将TheButton改为其它名称,则不会报错.如:


var TheButton = document.getElementById("TheButton");
//或
TestButton = document.getElementById("TheButton");

var TheButton = document.getElementById("TheButton");
//或
TestButton = document.getElementById("TheButton");

3. 字符串只替换第一个匹配

如下代码:


var fileName = "This is a title";
fileName=fileName.replace(" ","_");

var fileName = "This is a title";
fileName=fileName.replace(" ","_");

而实际上,fileName结果是”This_is a title”. 在JavaScript中,String.replace的第一个参数应该是正则表达式。所以,正确的做法是这样:


var fileName = "This is a title".replace(/ /g,"_");

var fileName = "This is a title".replace(/ /g,"_");

4. mouseout意味着mousein

事实上,这是由于事件冒泡导致的。IE中有mouseenter和mouseleave,但不是标准的。作者在此建议大家使用js库来解决问题。

5. parseInt是基于进制体系的

这个是常识,可是很多人给忽略了parseInt还有第二个参数,用以指明进制。比如,parseInt(“09″),如果你认为答案是9,那就错了。因为,在此,字符串以0开头,parseInt以八进制来处理它,在八进制中,09是非法,返回false,布尔值false转化成数值就是 因此,正确的做法是


parseInt("09", 10).
parseInt("09", 10).

6. forin会遍历所有的东西

有一段这样的代码:


var arr = [5,10,15]
var total = 1;
for ( var x in arr) {
total = total * arr[x];
}

var arr = [5,10,15]
var total = 1;
for ( var x in arr) {
total = total * arr[x];
}

运行得好好的,不是吗?但是有一天它不干了,给我返回的值变成了NaN, 晕。我只不过引入了一个库而已啊。原来是这个库改写了Array的prototype,这样,我们的arr平白无过多出了一个属性(方法),而forin会把它给遍历出来。
其实,就算没有引进库.它的结果也并不是数组所有元素的乘积,因为forin会遍历到数组的length属性.
所以这样做才是比较安全的:


for ( var x = 0; x < arr.length; x++) {
total = total * arr[x];
}

for ( var x = 0; x < arr.length; x++) {
total = total * arr[x];
}

其实,这也是污染基本类的prototype会带来危害的一个例证。

7. 事件处理器的陷阱

这其实只会存在使用作为对象属性的事件处理器才会存在的问题。比如window.onclick = MyOnClickMethod这样的代码,这会复写掉之前的window.onclick事件,还可能导致IE的内容泄露(sucks again)。在IE还没有支持DOM 2的事件注册之前,作者建议使用库来解决问题,比如使用YUI:


YAHOO.util.Event.addListener(window, "click", MyOnClickMethod);

这应该也属于常识问题,但新手可能容易犯错。

8. focus() 出错

新建一个input文本元素,然后把焦点挪到它上面,按理说,这样的代码应该很自然:


var newInput = document.createElement("input");
document.body.appendChild(newInput);
newInput.focus();
newInput.select();

var newInput = document.createElement("input");
document.body.appendChild(newInput);
newInput.focus();
newInput.select();

但是IE会报错。这是因为当你执行fouce()的时候,元素尚未可用。因此,我们可以延迟执行:


var newInput = document.createElement("input");
newInput.id = "TheNewInput";
document.body.appendChild(newInput);
//在01秒之后调用匿名函数获取焦点
setTimeout(function(){
document.getElementById('TheNewInput').focus();
document.getElementById('TheNewInput').select();}, 10);

var newInput = document.createElement("input");
newInput.id = "TheNewInput";
document.body.appendChild(newInput);
//在01秒之后调用匿名函数获取焦点
setTimeout(function(){
document.getElementById('TheNewInput').focus();
document.getElementById('TheNewInput').select();}, 10);

更详细的资料参见:http://realazy.org/blog/category/javascript-dom/

1document.write()完全替换之前页面内容
有这样一段代码:

开始

function init() {
document.write("现在时间是:" + Date() );
}
window.onload = init;

结束

开始

function init() {
document.write("现在时间是:" + Date() );
}
window.onload = init;

结束

上面代码块中的”开始”和”结束”两块不会输出.
当onload事件结束之后,如果再一次调用document.write()方法写进一段HTML,这段HTML会完全替换掉之前页面的内容.整个页面的源代码就变为了document.write()所写的内容.把上面的改为:

开始

function init() {
document.write("现在时间是:" + new Date() );
}
init()

结束

开始

function init() {
document.write("现在时间是:" + new Date() );
}
init()

结束

“开始”和”结束”就会正常输出.

1注意你name的值.

有这样一段代码:

//获取form的id
alert(document.forms[0].action);

//获取form的id
alert(document.forms[0].action);

可输出结果不是我们想要的”aa.htm”,而是一个”[object]“字符串.因为它得到的是myForm中的name为”action”的 input标签的值.更详细的内容请参考[url]https://bugzilla.mozilla.org /show_bug.cgi?id=322488
[/url]

后台数据传输不会影响到前台

也许你会说这是一非常低级的错误.但我还是想说下:
页面login.htm代码


xmlHttp.open("GET","check.htm",false);
xmlHttp.send();
alert(xmlHttp.responseText);

xmlHttp.open("GET","check.htm",false);
xmlHttp.send();
alert(xmlHttp.responseText)
;

页面check.htm代码


window.onload=checkLogin;
function checkLogin(){
//如果验证失败,弹出错误
alert("登录失败");
}

window.onload=checkLogin;
function checkLogin(){
//如果验证失败,弹出错误
alert("登录失败");
}

很多人习惯用这种方法来进行登录失败的提示.但是要注意:xmlHttp发送数据的时候是进行的后台发送,它所关心的,仅仅是send之后,得到所请求URL的响应.而check.htm页面所执行的一切,都是只在后台完成.不管它怎么跳转,或者alert(),或者close().都不会在界面中有任何显示.

—————————————————————————————–

在实践中,JavaScript的陷阱还有很多很多,大多是由于解析器的实现不到位而引起。这些东西一般都不会在教科书中出现,只能靠开发者之间的经验分享。希望大家有更好的分享。如发现其它的”陷阱”,我会继续增加内容.谢谢关注.

有话想说?