日期:2014-05-16 浏览次数:20477 次
<!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>
------解决方案--------------------
//错误一
this.answerToMyName = function(){
alert(this.name);//错误二
//这个this一旦你在后面使用button.onclick = newInstance.answerToMyName;的时候,这个this指向的是button而非你的newInstance。
};
你的写法是无法作为一个对象的方法被调用的