Composing Prototypes

Contact Us or call 1-877-932-8228
Composing Prototypes

Composing Prototypes

As your JavaScript code grows more complex, you'll often find it helpful to combine prototypes: member data in one prototype may consist of objects from another prototype. Consider the following example, in which we create a "Team" prototype (to represent a sports team); a member of each team is an array of people who are players on that team. Each element of the players array is itself an object of the Person prototype:

Code Sample:

AdvancedObjects/Demos/multipleobjects.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Multiple Prototypes</title>
	<script>
		var Person = function(fname, lname, age) {
			this.fname = fname;
			this.lname = lname;
			this.age = age;
			this.fullName = function() {
				return this.fname + ' ' + this.lname;
			}
		}

		var Team = function(teamName, sport) {
			this.teamName = teamName;
			this.sport = sport;
			this.players = [];
			            this.addPlayer = function(person) {
				this.players.push(person);
			}
			            this.toString = function() {
				var str = '<strong>' + this.teamName + '</strong>';
				str += '<ul>';
				for (let p in this.players) {
					if (this.players.hasOwnProperty(p)) {
						let person = this.players[p];
						str += '<li>' + person.fname + ' ' + person.lname + '</li>';
					}
				}
				str += '</ul>';
				return str;
			}
		}
	</script>
</head>
<body>
	<h1>Multiple Prototypes</h1>
	<script>
		var jdoe = new Person('Jane', 'Doe', 32);
		var afung = new Person('Adam', 'Fung', 11);
		
		var Tigers = new Team('The Tigers', 'soccer');
		Tigers.addPlayer(jdoe);
		Tigers.addPlayer(afung);

		document.write('Here is my team:<br><br>');
		document.write(Tigers);
	</script>
</body>
</html>

Code Explanation

Note that we are using ES2015 code here. We again define a Person prototype. We also define a Team prototype, with members for the name of the team and the type of sport. Each Team object also has access to two methods:

  1. Function addPlayer(person) adds a Person object to the this.players array.
  2. Function toString() returns a string-ified version of the Team object: the bolded name of the team and an unordered list of the team's players, which we generate by iterating over the array of team members.

The toString() method deserves special mention: toString() is a built-in JavaScript function - a method of the Object prototype. By overriding it - that is, by writing a custom version of toString() that is specific to and appropriate for our particular Team prototype - we tell JavaScript how it is that we would like any object of Team to be turned into a string. This allows us to use the shorthand document.write(Tigers) to write an object of Team to the screen or to turn it into a string for any other purpose.

We'll ask you to try out these concepts in the next exercise:

Next