读书人

看一段代码啊该怎么处理

发布时间: 2012-03-03 15:33:03 作者: rapoo

看一段代码啊
<script type="text/javascript">

var whoami = function(name,email) {
this.name = name;
this.email = email;

answerToMyName:function() {
alert(this.name);
};

answerToMyEmail:function() {
alert(this.email);
};
};

var addHandler = function() {
var newInstance = new whoami('smellcode','smellcode@gmail.com');
var button = document.getElementById('buttonId');
button.onclick = newInstance.answerToMyName;
};

window.onload = addHandler;
</script>

<body>
<input type="button" id="buttonId" name="buttonName" value="点击"/>
</body>

怎么没用?


[解决办法]
var whoami = function(name,email)
不是对象吧,貌似应该用new whoami = function(name,email)
[解决办法]
answerToMyName:function() {
alert(this.name);
};
在ff下报错
[解决办法]

JScript code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript">var whoami = function(name,email) {      this.name = name;      this.email = email;      this.answerToMyName = function() {          alert(this.name);      };      this.answerToMyEmail = function() {          alert(this.email);      };    };    var addHandler = function() {      var newInstance = new whoami('smellcode','smellcode@gmail.com');      var button = document.getElementById('buttonId');      button.onclick = newInstance.answerToMyName;    };    window.onload = addHandler;</script></head><body>    <input type="button" id="buttonId" name="buttonName" value="点击"/></body></html>
[解决办法]
JScript code
//错误一this.answerToMyName = function(){  alert(this.name);//错误二  //这个this一旦你在后面使用button.onclick = newInstance.answerToMyName;的时候,这个this指向的是button而非你的newInstance。};你的写法是无法作为一个对象的方法被调用的 

读书人网 >JavaScript

热点推荐