下面的代码,alert出来的结果,说明这个时候t是return的那个html对象,而非Test的实例。为啥啊?我知道一般写成类的形式是不带return的。
[code]
<input type="text" name="myText">
<script language="JavaScript">
<!--
function Test(id){
this.type = 'class test';
return document.getElementById(id);
}
var t = new Test('myText');
alert(t.type); //结果是text,看来这时候t是myText这个html对象而非Test类的实例
//-->
</script>
[/code]
[code]
<input type="text" name="myText">
<script language="JavaScript">
<!--
function Test(id){
this.type = 'class test';
return document.getElementById(id);
}
var t = new Test('myText');
alert(t.type); //结果是text,看来这时候t是myText这个html对象而非Test类的实例
//-->
</script>
[/code]
本文探讨了一个有趣的JavaScript构造函数案例,该函数返回了一个DOM元素而不是创建的新实例。通过这段代码,我们了解到构造函数中使用return语句的影响,并讨论了为何返回的会是HTML对象而非预期的构造函数实例。
999

被折叠的 条评论
为什么被折叠?



