Introduction to JavaScript Fall 2011 Class 4

Jump to: navigation, search

Back to Introduction to JavaScript Fall 2011

Contents

Lecture

Objects

Method 1

 var object = new Object;  
 	
 object.property1 = 47;
 object.property2 = "is the answer";
 object.method1 = function(name){
 	console.log("Hello " + name + ", " + this.property1 + " " + this.property2 + ".");
 }
 object.method1("Dave");

Method 2

 var object2 = {
 	"property1" : 47,
 	"property2" : "is not the answer",
 	"method1" : function(name) {
 		console.log("Hello " + name + ", " + this.property1 + " " + this.property2 + ".");
 	},
 	"property 3" : "this is what a 3rd property would look like"
 }
 object2.method1("Jerry");

Arrays

Method 1

 var turtles = new Array;
 
 turtles[0] = "Raph";
 turtles[1] = "Don";
 turtles[2] = "Mike";
 turtles[3] = function(){
 	console.log(this[1] + ", " + this[0]);
 }
 turtles[3]();

Method 2

 var turtles2 = ["Raph", "Don", "Mike", function(){
 	console.log(this[1] + ", " + this[0]);
 }];

Method 3

 var turtles3 = new Array;
 turtles3.push("Don");
 turtles3.push("Raph");
 turtles3.push("Bob");
 console.log(turtles3[0]);
 console.log(turtles3[2]);

For Loops

 var i;
 for(i=0;i<turtles.length;i++){
 	console.log(turtles[i]);
 }


Now, with an array full of objects, popularly known as JSON

 var characters = [{
 	"name" : "William Adama",
 	"nickname" : "Husker",
 	"gender" : "male"
 }, {
 	"name" : "Lee Adama",
 	"nickname" : "Apollo",
 	"gender" : "male"
 }, {
 	"name" : "Gaius Baltar",
 	"nickname" : "Doctor Jerkface",
 	"gender" : "male"
 }, {
 	"name" : "Sharon Valerii",
 	"nickname" : "Boomer",
 	"gender" : "female"
 }, {
 	"name" : "Laura Roslin",
 	"nickname" : "Madam President",
 	"gender" : "female"
 }, {
 	"name" : "Kara Thrace",
 	"nickname" : "Starbuck",
 	"gender" : "female"
 }];
 var ladies = document.createElement('ul'), fellows = document.createElement('ul'), content = document.getElementById('content'), nickname = document.createElement('div'), nameContainer = document.createElement('span'), i;
 
 nameContainer.appendChild(document.createTextNode(' '));
 nickname.appendChild(document.createTextNode('Nickname: '));
 nickname.appendChild(nameContainer);
 content.appendChild(ladies);
 content.appendChild(fellows);
 content.appendChild(nickname);
 
 for( i = 0; i < characters.length; i++) {
 	var li = document.createElement('li');
 	li.appendChild(document.createTextNode(characters[i].name));
 	li.nickname = characters[i].nickname;
 	li.onclick = showNickname;
 	if(characters[i].gender === "female") {
 		ladies.appendChild(li);
 	} else if(characters[i].gender === "male") {
 		fellows.appendChild(li);
 	} else {
 		console.log("I don't have a bucket for that.");
 	}
 }
 function showNickname() {
 	nameContainer.firstChild.nodeValue = this.nickname;
 }

Homework

In-Class 5

In-Class 5 details

Assignment 4

Assignment 4 details