<html>
<head>
<script type="text/javascript">
var liu={}
liu.speaked=function(str){
alert(str);
this.speaker=str;
try{
this.speakstr()//speaked的一个方法
}catch(e){
alert(e)
}
} liu.speaked.prototype={
speakstr:function(){
alert("my name is"+ this.speaker);
}
}
</script>
</head>
<body>
<input type="button" value="haha" onclick="liu.speaked('sdf')"/>
</body>
</html>
总是执行catch里的内容,我郁闷老半天了,大家说哪有问题,谢谢了
若你在按钮点击中调用liu.speaked("sdf").
只是相当于执行了liu.speaked()这个函数.并没有创建一个liu.speaked类型的对象.
所以liu.speaked中的prototype属性无法发挥作用,自然也就无法执行speakstr方法了.进而报出异常了.解决办法是:
将body中的代码改为
<input type="button" value="haha" onclick="new liu.speaked('sdf');" />
这样创建了一个新的liu.speaked的对象.
调用speakstr方法就不会出现"对象无此方法或属性"的错误了.
<head>
<script type="text/javascript"> var liu={}
liu.speaked=function(str){
this.speaker=str;
try{
this.speakstr()
}catch(e){
alert(e.message)
}
}
liu.speaked.prototype={
speakstr:function(){
alert("my name is"+ this.speaker);
}
}
var aaa = new liu.speaked();
</script>
</head>
<body>
<input type="button" value="haha" onclick="aaa.speaked('sdf')"/>
</body>
</html>
<html>
<head>
<script type="text/javascript"> var liu={}
liu.speaked=function(str){
this.speaker=str;
try{
this.speakstr()
}catch(e){
alert(e.message)
}
}
liu.speaked.prototype={
speakstr:function(){
alert("my name is "+ this.speaker);
}
}
var aaa = new liu.speaked("str");//--------------加的
</script>
</head>
<body>
<input type="button" value="haha" onclick="aaa.speaked()"/><!--改的-->
</body>
</html>
<head> <script type="text/javascript">
var liu={}
liu.speaked=function(str){
alert(str);
this.speaker=str;
try{
this.speaked.prototype.speakstr()//speaked的一个方法
}catch(e){
alert(e)
}
} liu.speaked.prototype={
speakstr:function(){
alert("my name is"+ this.speaker);
}
}
</script></head>
<body>
<input type="button" value="haha" onclick="liu.speaked('sdf')" />
</body>
</html>
看这样行