OO JavaScript - onclick of form button

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
zenabi
Forum Commoner
Posts: 84
Joined: Mon Sep 08, 2003 5:26 am
Location: UK

OO JavaScript - onclick of form button

Post by zenabi »

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:

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?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: OO JavaScript - onclick of form button

Post by Weirdan »

You can fix it by using closures like this:

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) {
		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>
zenabi
Forum Commoner
Posts: 84
Joined: Mon Sep 08, 2003 5:26 am
Location: UK

Post by zenabi »

Thank you Weirdan! It's a shame I can't use the prototype way to make things a little neater, but if it works it works :D
Post Reply