<!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?
<!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) {
var me = this; // <================= copy this pointer to the local variable
this.firstname = firstname;
document.getElementById('button').onclick = this.talk;
this.talk = function() { // <====================== define the method inside the constructor
alert("My name is " + me.firstname); // <============== me variable is available here as a result of closure
}
}
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>