日期:2014-05-16  浏览次数:20385 次

看一段代码啊
<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。
};
你的写法是无法作为一个对象的方法被调用的