OO JavaScript - onclick of form button
Posted: Mon Dec 12, 2005 4:20 am
I'm a beginner to OOP techniques and I'm having a little trouble appending a function to the onclick event of a form button (unobtrusive JavaScript).
Full code:
The result I get is "My name is undefined". I realise that, in this case, the this in the talk method is referring to the button object and not my Person object. How do I fix this?
Full code:
Code: Select all
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
function Person(firstname) {
this.firstname = firstname;
document.getElementById('button').onclick = this.talk;
}
Person.prototype.talk = function () {
alert("My name is " + this.firstname);
}
window.onload = function () {
var homer = new Person('Homer');
}
</script>
</head>
<body>
<form action="#">
<fieldset>
<input type="button" value="Button" id="button" />
</fieldset>
</form>
</body>
</html>The result I get is "My name is undefined". I realise that, in this case, the this in the talk method is referring to the button object and not my Person object. How do I fix this?