Notes for CodeSchool's Javascript Roadtrip 3

The following is my notes from Codeschools javascript road trip part 3 (https://www.codeschool.com/courses/javascript-road-trip-part-3). I have also included my answers to challenges. Please also see attached text file for better formatting.


Code School JavaScript Roadtrip 3

* notes 1.1

FUNCTION EXPRESSIONS

functions can be assigned to variables
var diff = function optName (a, b) {
return a*a - b*b;
}; must end in semicolon

diff(9,5) 56

anonymous function
no need to name a function assigned to a variable

logging a function variable with console.log will output function

* challenge 1.2

var runAway = function () {
var toAlert = "";
for (var i = 0; i < 5; i++) {
toAlert = toAlert + "Lions, Tigers, and Bears, Oh My!!\n";
}
alert(toAlert);
};

* challenge 1.3

var people = 100;
var rain = 2;
var sharks = 5;

var fearGenerated = function(numPeeps, rainInInches, numSharks) {
var rainFear = numPeeps * rainInInches;
var sharkFear = numSharks * numSharks * numSharks;
var totalFear = sharkFear + rainFear;
return totalFear;
};

var fear = fearGenerated(people, rain, sharks);

* challenge 1.4

alert(fearGenerated);

* challenge 1.5

var fear = fearGenerated(numPeeps, rainInInches, numSharks);

var fearMessage = function() {
// Insert conditional statements here
if (fear < 200) {
return(confirm("Fear Level: LOW\nStill wanna ride?"));
} else if (fear <= 300) {
return(confirm("Fear Level: MEDIUM\nThink you'll make it?"));
}
};

function confirmRide(confirmToGo) {
return confirmToGo();
}

var startRide = confirmRide(fearMessage);

* notes 1.6

PASSING FUNCTION EXPRESSIONS AS PARAMETERS

map method
the map method of an array, runs a function on each array cell

var nums = [1,2,3]
var results = nums.map(function(arrayCell) {return arrayCell*2;});

* challenge 1.7

var passengers = [ ["Thomas", "Meeks"],
["Gregg", "Pollack"],
["Christine", "Wong"],
["Dan", "McGaw"] ];

var modifiedNames = passengers.map(function(arrayCell){ return arrayCell[0] +" "+ arrayCell[1]; });

* challenge 1.8

var modifiedNames = [ "Thomas Meeks",
"Gregg Pollack",
"Christine Wong",
"Dan McGaw" ];

modifiedNames.map(function(arrayCell){ alert("Yo, "+arrayCell); });

* challenge 1.9

var puzzlers = [function(i) {return(3 * i - 8);},
function(i) {return((i + 2)*(i + 2)*(i + 2));},
function(i) {return(i * i - 9);},
function(i) {return(i % 4);},
];

* notes 1.10

RETURNING FUNCTIONS

functions can return functions

shift() method
on arrays; removes first cell and returns value
like pop() method, array will be shortened by one
shift will always return a cell

to invoke return expression:
if assigned to variable use parenthesis
var rFunc = funcRet(param);
rFunc();

returned functions can be called immediately
by adding parenthisses to function call
funcRet(param)();

* challenge 1.11

function adventureSelector(userChoice) {
// return anonymous functions inside conditional blocks
if (userChoice == 1) {
return(function(){alert("You selected the Vines of Doom!");});
} else if (userChoice == 2) {
return(function(){alert("Looks like you want the Lake of Despair!");});
} else {
return(function(){alert("The Caves of Catastrophe!");});
}
}

* challenge 1.12

adventureSelector(3)();

* challenge 1.13

var puzzlers = [
function(a) { return 8 * a - 10; },
function(a) { return (a - 3) * (a - 3) * (a - 3); },
function(a) { return a * a + 4; },
function(a) { return a % 5; }
];
var start = 2;

var applyAndEmpty = function(input, queue) {
for (var i=queue.length; i>=1; i--) {
input = queue.shift()(input);
}
return input;
};

alert(applyAndEmpty(start, puzzlers));

* challenge 1.14

alert(puzzlers[puzzlers[1](3)](puzzlers[3](9)));

* notes 2.1

CLOSURES

closure happens when a function returns another function
a closure wraps up an entire environment, binding necessary variables from other scopes
a closure can make the creation of similar functions very efficent

* challenge 2.2

function mystery() {
var secret = 6;
function mystery2(multiplier) {
multiplier *= 3;
return secret * multiplier;
}
return mystery2;
}

var hidden = mystery();
var result = hidden(3);

alert(54);

* challenge 2.3

function mystery(input) {
var secret = 5;
function mystery2(multiplier) {
multiplier *= input;
return secret * multiplier;
}
return mystery2;
}

var hidden = mystery(4);
var result = hidden(2);

alert(40);

* challenge 2.4

function mystery(input) {
var secret = 4;
input += 2;
function mystery2(multiplier) {
multiplier *= input;
return secret * multiplier;
}
return mystery2;
}

function mystery3(param) {
function mystery4(bonus) {
return param(6) + bonus;
}
return mystery4;
}

var hidden = mystery(3);
var jumble = mystery3(hidden);
var result = jumble(2);

alert(122);

* challenge 2.5

function warningMaker(obstacle) {
var warnFunc = function(){
alert("Beware! There have been "+ obstacle +" sightings in the Cove today!");
};
return warnFunc;
}

* challenge 2.6

function warningMaker(obstacle) {
return function() {
alert("Beware! There have been " + obstacle + " sightings in the Cove today!");
};
}

// build your warning message here
var icebergAlert = warningMaker("iceberg");
icebergAlert();

* challenge 2.7

function warningMaker(obstacle) {
return function(number, location) { // set parameters
alert("Beware! There have been " + obstacle +
" sightings in the Cove today!\n" +
// finish the warning message here
number + " have been spotted at the " + location + "!"
);
};
}

* challenge 2.8

function warningMaker(obstacle) {
return function(number, location) {
alert("Beware! There have been " + obstacle +
" sightings in the Cove today!\n" +
number + " have been spotted at the " +
location + "!");
};
}

var killerPenguinAlert = warningMaker("killer penguin");
var polarBearAlert = warningMaker("polar bear");
var icebergAlert = warningMaker("iceberg");
var flashBlizzardAlert = warningMaker("flash blizzard");
var snowYetiAlert = warningMaker("snow yeti");

// call the two functions here
killerPenguinAlert(6, "Ice Caves");
snowYetiAlert(1, "Blizzard Beach");

* notes 2.9

bound variables can be modified after closure

* challenge 2.10

function warningMaker(obstacle) {
// create a count
var count = 0;
return function(number, location) {
// keep track of warnings
count++;
alert("Beware! There have been " + obstacle +
" sightings in the Cove today!\n" + number + " have been spotted at the " + location + "!\n" +
// finish the warning message here
"This is alert #" + count + " today for " + obstacle + " danger."
);
};
}

* challenge 2.11

function warningMaker(obstacle) {
var count = 0;
var zones = [];
return function(number, location) {
count++;
var list = "";
// add each location to the zones array
zones.push(location);
// add each zone to the list string
for (var i = 0; i < zones.length; i++) {
list += "\n"+ zones[i];
}
alert("Beware! There have been " + obstacle +
" sightings in the Cove today!\n" +
number + " have been spotted at the " +
location + "!\n" +
"This is alert #" + count +
" today for " + obstacle + " danger.\n" +
// finish the warning message here
"Current danger zones are:" +
list
);
};
}

* challenge 2.12

function warningMaker(obstacle) {
var count = 0;
var zones = [];
return function(number, location) {
count++;
var list = "";
// push an array with location and number
zones.push([number, location]);
for (var i = 0; i < zones.length; i++) {
// replace location and number with appropriate code
list += zones[i][1] + " (" + zones[i][0] + ")" + "\n";
}
alert("Beware! There have been " + obstacle +
" sightings in the Cove today!\n" +
number + " have been spotted at the " +
location + "!\n" +
"This is alert #" + count +
" today for " + obstacle + " danger.\n" +
"Current danger zones are:\n" +
list);
};
}

* notes 2.13

variable values are bound at the time of return
ex: in loops, indexes will advance to end

closures bind values at last moment
we have to pay close attention to return times and variable states

* challenge 2.14

function assignLaser(shark, sharkList) {
for (var i = 0; i < sharkList.length; i++) {
if (shark == sharkList[i]) {
return function() {
alert("Yo, " + shark + "!\n" +
"Visit underwater strapping station " +
(i + 1) + " for your sweet laser.");
};
}
}
}

* challenge 2.15

function makeTargetAssigner(sharks, targets) {
// insert your code here
return function(shark) {
for (var i=0; i if (shark == sharks[i]) {
alert("What up, "+ shark +"!\n"+
"There\'ve been "+ targets[i] +" sightings in our \'hood!\n"+
"Time for a swim-by lasering, homie!");
}
}
};
}

var getTargetFor = makeTargetAssigner(listOfSharks,
listOfTargets);
getTargetFor("Ice Teeth");

* notes 3.1

LOAD ORDER - HOISTING

the importance of load order
ensuring that every line of code can execute when needed

within a scope a compiler will:
sets memory aside for variables
set memory aside for declared functions
run executable code

hoisting is moving code to the top of the compiled code
necessary variables - hoisted
declared function - hoisted

function expressions are never hoisted

solutions
move return statements to bottom of scope
use declared functions

* challenge 3.2

function thisIsWeird() {
function secret() {
var unused3;
}
var result;
function secret() {
var unused1;
}
// The following line of code assigns a
// secret function to the variable result.
result = secret;
function secret() {
var unused2;
}
return result;
}

console.log("unused2");

* challenge 3.3

function theBridgeOfHoistingDoom() {
var ring = undefined;
var power = undefined;
function balrog() {
return "whip";
}
function wizard() {
return "white";
}
function elf() {
return "immortal";
}
ring = wizard;
wizard = balrog;
return wizard();
}

* challenge 3.4

function theBridgeOfHoistingDoom() {
var sword = undefined;
var dwarf = undefined;
var fall = undefined;
var ring = undefined;
function fellowship() {
return "friends";
}
sword = "sting";
dwarf = function() {
return "axe";
};
fall = "Fly you fools!";
fellowship = function() {
return "broken";
};
ring();
return sword;
}

* challenge 3.5

console.log("ERROR");

* notes 4.1

OBJECTS

an object is a container of related information
properties group data in an object
properties can refer to numbers, strings, arrays, functions, and objects

objects can be created multiple ways
object literal
var myBox = {height:1};
properties are separated by commas

variables as property values will reference outside object
var books = ["one", "two"];
var myBox = {height:1,contents:books};

contents of properties can be accessed via dot notation
myBox.height 1

Properties can be added to objects via dot notation
contents of properties can be set via dot notation
myBox.nevProp = 3;

properties can be accessed and set via bracket notation
myBox["books"]
spaces can be added to property names this way
property name can also be formulaic
myBox["book"+1]

delete keyword removes properties from objects
delete myBox.length
always returns true

to access object inside of objects
myBox.dimensions.height
myBox["dimensions"]["height"];

* challenge 4.2

var vehicle1 = {type:"Motorboat",
capacity:6,
storedAt:"Ammunition Depot"};
var vehicle2 = {type:"Jet Ski",
capacity:1,
storedAt:"Reef Dock"};
var vehicle3 = {type:"Submarine",
capacity:8,
storedAt:"Underwater Outpost"};

* challenge 4.3

var vehicle1 = {type: "Motorboat", capacity: 6, storedAt: "Ammunition Depot"};
var vehicle2 = {type: "Jet Ski", capacity: 1, storedAt: "Reef Dock"};
var vehicle3 = {type: "Submarine", capacity: 8, storedAt: "Underwater Outpost"};

// log the property value to the console
console.log(vehicle1.capacity);

* challenge 4.4

var vehicle1 = {type: "Motorboat", capacity: 6, storedAt: "Ammunition Depot"};
var vehicle2 = {type: "Jet Ski", capacity: 1, storedAt: "Reef Dock"};
var vehicle3 = {type: "Submarine", capacity: 8, storedAt: "Underwater Outpost"};

// create vehicles array
var vehicles = [vehicle1, vehicle2, vehicle3];

// build findVehicle function expression
var findVehicle = function(name, list) {
for (var i=0; i<=list.length; i++) {
if (list[i].type == name) {
return list[i].storedAt;
}
}
};

// call findVehicle
findVehicle("Submarine", vehicles);

* challenge 4.5

var vehicle1 = {type: "Motorboat", capacity: 6, storedAt: "Ammunition Depot"};
var vehicle2 = {type: "Jet Ski", capacity: 1, storedAt: "Reef Dock"};
var vehicle3 = {type: "Submarine", capacity: 8, storedAt: "Underwater Outpost"};

// add and adjust object properties here
vehicle1.capacity += 4;
vehicle2.submersible = false;
vehicle3.weapon = "Torpedoes";
vehicle1.submersible = false;
vehicle2.weapon = "Lasers";
vehicle3.capacity *= 2;
vehicle1.weapon = "Rear-Mounted Slingshot";
vehicle3.submersible = true;

# challenge 4.6

var vehicle1 = {type: "Motorboat", capacity: 6, storedAt: "Ammunition Depot"};
var vehicle2 = {type: "Jet Ski", capacity: 1, storedAt: "Reef Dock"};
var vehicle3 = {type: "Submarine", capacity: 8, storedAt: "Underwater Outpost"};

vehicle1.capacity += 4;
vehicle2.submersible = false;
vehicle3.weapon = "Torpedoes";
vehicle1.submersible = false;
vehicle2.weapon = "Lasers";
vehicle3.capacity *= 2;
vehicle1.weapon = "Rear-Mounted Slingshot";
vehicle3.submersible = true;

// add properties and assign values
vehicle3["# of weapons"] = 8;
vehicle2["# of weapons"] = 4;
vehicle1["# of weapons"] = 1;

* challenge 4.7

var superBlinders = [
["Firelight", 4000],
["Solar Death Ray", 6000],
["Supernova", 12000]
];

var lighthouseRock = {
gateClosed: true,
bulbs: [200, 500, 750],
capacity: 30,
secretPassageTo: "Underwater Outpost"
};

// remove bulbs property from lighthouseRock
delete lighthouseRock.bulbs;

// add weaponBulbs property to lighthouseRock
lighthouseRock.weaponBulbs = superBlinders;

// log the correct weaponBulbs array value to the console
console.log(lighthouseRock.weaponBulbs[2][0]);

* challenge 4.8

var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];

var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 0
};

function addRanger(location, name, skillz, station) {
// increment the number of rangers property
location.numRangers++;
// add the ranger property and assign a ranger object
location["ranger" + location.numRangers] = {name:name, skillz:skillz, station:station};
}

// call addRanger three times to add the new rangers
addRanger(lighthouseRock, "Nick Walsh", "magnification burn", 2);
addRanger(lighthouseRock, "Drew Barontini", "uppercut launch", 3);
addRanger(lighthouseRock, "Christine Wong", "bomb defusing", 1);

* challenge 4.9

var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];

var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 3,
ranger1: {name: "Nick Walsh", skillz: "magnification burn", station: 2},
ranger2: {name: "Drew Barontini", skillz: "uppercut launch", station: 3},
ranger3: {name: "Christine Wong", skillz: "bomb defusing", station: 1}
};

function dontPanic(location) {
var list = "Avast, me hearties!\n" +
"There be Pirates nearby! Stations!\n";
// loop through the rangers and append to list
for (var i=0; i location["ranger"+i] —————————————————————————
list += location["ranger"+i]["name"] + ", man the " +
location.weaponBulbs[location["ranger"+i]["station"]] + "!";
}
alert(list);
}

dontPanic(lighthouseRock);

* notes 4.10

OBJECT FUNCTIONALITY

properties can be assigned function expressions
these are called methods
they can be created in object literal or with dot notation

myBox.addThing = function(name) {
this.contents.push(name);
}
this refers to current object

* challenge 4.11

var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];

var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 3,
ranger1: {name: "Nick Walsh", skillz: "magnification burn", station: 2},
ranger2: {name: "Drew Barontini", skillz: "uppercut launch", station: 3},
ranger3: {name: "Christine Wong", skillz: "bomb defusing", station: 1},
addRanger: function(name, skillz, station) {
this.numRangers++;
this["ranger" + this.numRangers] = {
name: name,
skillz: skillz,
station: station
};
}
};

* challenge 4.12

var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];

var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 3,
ranger1: {name: "Nick Walsh", skillz: "magnification burn", station: 2},
ranger2: {name: "Drew Barontini", skillz: "uppercut launch", station: 3},
ranger3: {name: "Christine Wong", skillz: "bomb defusing", station: 1},
addRanger: function(name, skillz, station) {
this.numRangers++;
this["ranger" + this.numRangers] = {
name: name,
skillz: skillz,
station: station
};
}
};
// call the addRanger method on lighthouseRock
lighthouseRock.addRanger("Jordan Wade","dual-wield hand crossbow",4);

* challenge 4.13

var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];

var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 3,
ranger1: {name: "Nick Walsh", skillz: "magnification burn", station: 2},
ranger2: {name: "Drew Barontini", skillz: "uppercut launch", station: 3},
ranger3: {name: "Christine Wong", skillz: "bomb defusing", station: 1},
ranger4: {name: "Jordan Wade", skillz: "dual-wield hand crossbow", station: 4},
addRanger: function(name, skillz, station) {
this.numRangers++;
this["ranger" + this.numRangers] = {
name: name,
skillz: skillz,
station: station
};
}
};

// create addBulb function property here
lighthouseRock.addBulb = function(name, wattage) {
this.weaponBulbs.push([name, wattage]);
};

* challenge 4.14

lighthouseRock.addBulb = function(name, wattage) {
this.weaponBulbs.push([name, wattage]);
};

// call addBulb and pass in the correct arguments
lighthouseRock.addBulb("Blasterbright", 5000);
lighthouseRock.addBulb("Sight Slayer", 1800);
lighthouseRock.addBulb("Burner of Souls", 7500);

* challenge 4.15

var vehicle3 = {
type: "Submarine", capacity: 8, storedAt: "Underwater Outpost",
ranger1: {name: "Gregg Pollack", skillz: "Lasering", dayOff: "Friday"},
ranger2: {name: "Bijan Boustani", skillz: "Working", dayOff: "Saturday"},
ranger3: {name: "Ashley Smith", skillz: "Torpedoing", dayOff: "Friday"},
ranger4: {name: "Mark Krupinski", skillz: "Sniping", dayOff: "Wednesday"},
numRangers: 4
};

function relieveDuty(vehicle, day) {
var offDuty = [];
var onDuty = [];
for (var i = 1; i <= vehicle.numRangers; i++) {
if (vehicle["ranger"+i].dayOff == day) {
offDuty.push(vehicle["ranger"+i]);
} else {
onDuty.push(vehicle["ranger"+i]);
}
delete vehicle["ranger"+i];
}
vehicle.numRangers -= offDuty.length;
for (var j = 1; j <= vehicle.numRangers; j++) {
vehicle["ranger"+j] = onDuty.shift();
}
return offDuty;
}

var offToday = relieveDuty(vehicle3, "Friday");

* notes 4.16

objects do not have a length property

for-in loops iterates through property names in an object
for (key in myBox) {}

* challenge 4.17

var rockSpearguns = {
Sharpshooter: {barbs: 2, weight: 10, heft: "overhand"},
Pokepistol: {barbs: 4, weight: 8, heft: "shoulder"},
Javelinjet: {barbs: 4, weight: 12, heft: "waist"},
Firefork: {barbs: 6, weight: 8, heft: "overhand"},
"The Impaler": {barbs: 1, weight: 30, heft: "chest"}
};

// build listGuns
function listGuns(guns) {
for (speargun in guns) {
console.log(speargun);
}
}

// call listGuns and pass in rockSpearguns
listGuns(rockSpearguns);

* challenge 4.18

var rockSpearguns = {
Sharpshooter: {barbs: 2, weight: 10, heft: "overhand"},
Pokepistol: {barbs: 4, weight: 8, heft: "shoulder"},
Javelinjet: {barbs: 4, weight: 12, heft: "waist"},
Firefork: {barbs: 6, weight: 8, heft: "overhand"},
"The Impaler": {barbs: 1, weight: 30, heft: "chest"}
};

function listGuns(guns) {
for (var speargun in guns) {
// modify the log message here
console.log("Behold! "+ speargun +", with "+ guns[speargun]["heft"] +" heft!");
}
}

listGuns(rockSpearguns);

* challenge 4.19

var rockSpearguns = {
Sharpshooter: {barbs: 2, weight: 10, heft: "overhand"},
Pokepistol: {barbs: 4, weight: 8, heft: "shoulder"},
Javelinjet: {barbs: 4, weight: 12, heft: "waist"},
Firefork: {barbs: 6, weight: 8, heft: "overhand"},
"The Impaler": {barbs: 1, weight: 30, heft: "chest"}
};

// convert listGuns function
rockSpearguns["listGuns"] = function() {
for (var property in this) {
if (this[property]["heft"] != undefined) {
console.log("Behold! " + property + ", with " + this[property]["heft"] + " heft!");
}
}
};

// call listGuns using bracket notation on rockSpearguns
rockSpearguns["listGuns"]();

* notes 5.1

INHERITENCE - PROTOTYPES

when generic objects are created they have hidden properties; for instance
valueOf, constructor, toLocaleString, toString, is PrototypeOf, propertyIsEnumerable, hasOwnProperty

an objects parent is its prototype
the object prototype is the highest level and passes the above properties

passing down properties is called inheritance
avoids over-coding properties and methods into similar objects

arrays inherit from the array prototype getting their methods
pop, push, shift, length, reverse, sort, reduce, join, slice

strings also inherit from a string object
length, charAt, trim, concat, indexOf, replace, ….

there is also number and function prototypes

all prototypes come from the Object prototype
this a string prototype inherits from the object prototype

inheritance avoids duplicate memory storage

properties are owned by prototypes not by inheriting object

adding inheritable properties to prototypes
String.prototype.newFunc = function(param) {};
all strings would now have access to newFunc

* challenge 5.2

Array.prototype.countCattle = function(kind) {
var numKind = 0;
for (var i=0; i<=this.length(); i++) {
if (this[i]["type"] == kind) {
numKind++;
}
}
return numKind;
};

* challenge 5.3

Array.prototype.countCattle = function(kind) {
var numKind = 0;
for (var i = 0; i < this.length; i++) {
if (this[i].type == kind) {
numKind++;
}
}
return numKind;
};
alert(canyonCows.countCattle("calf") + valleyCows.countCattle("bull") + forestCows.countCattle("cow"));

* challenge 5.4

Object.prototype.noCalvesYet = function() {
if ((this.type == "cow") && (this.hadCalf === null)) {
return true;
} else {
return false;
}
};

Array.prototype.countForBreeding = function() {
var numToBreed = 0;
for (var i = 0; i < this.length; i++) {
if (this[i].noCalvesYet()) {
numToBreed++;
}
}
return numToBreed;
};

* challenge 5.5

Object.prototype.noCalvesYet = function() {
if (this.type == "cow" && this.hadCalf == null) {
return true;
} else {
return false;
}
};

Array.prototype.countForBreeding = function() {
var numToBreed = 0;
for (var i = 0; i < this.length; i++) {
if (this[i].noCalvesYet()) {
numToBreed++;
}
}
return numToBreed;
};

// set up your numPriorityCows variable
var numPriorityCows = 0;
numPriorityCows += canyonCows.countForBreeding();
numPriorityCows += valleyCows.countForBreeding();
numPriorityCows += forestCows.countForBreeding();
numPriorityCows += badlandsCows.countForBreeding();

// alert the correct message with the total
alert("Herd-merger has indicated "+ numPriorityCows +" cows of top breeding priority.");

* notes 5.6

using inheritance you can create new objects from existing objects

var magicshoe = object.create(shoe); -> magic shoe inherits all properties from shoe

isProtoype of will find out if object on left is ancestor of parameter
shoe.isPrototypeOf(magicshoe);

constructor - allows to setup inheritance and assign certain property values
function Shoe(size, color) { <- should always begin with a capital
this.size = size;
this.color = color;
}
var boot = new Shoe(10, 'red');

new keyword produces a new instance of a class

add properties to object prototype to give all instances an inherited property
shoe.prototype = {width:"wide"}

prototypes can use the 'this' keyword to reference values in descendent object

* challenge 5.7

var genericPost = {
x: 0,
y: 0,
postNum: undefined,
connectionsTo: undefined,
sendRopeTo: function(connectedPost) {
if (this.connectionsTo == undefined) {
var postArray = [];
postArray.push(connectedPost);
this.connectionsTo = postArray;
} else {
this.connectionsTo.push(connectedPost);
}
}
};

// create post1 and post2
var post1 = Object.create(genericPost);
var post2 = Object.create(genericPost);

// modify the post properties
post1.x = -2;
post1.y = 4;
post1.postNum = 1;
post2.x = 5;
post2.y = 1;
post2.postNum = 2;

// connect the posts together
post1.sendRopeTo(post2);
post2.sendRopeTo(post1);

* challenge 5.8

var genericPost = {
x: 0,
y: 0,
postNum: undefined,
connectionsTo: undefined,
sendRopeTo: function(connectedPost) {
if (this.connectionsTo == undefined) {
var postArray = [];
postArray.push(connectedPost);
this.connectionsTo = postArray;
} else {
this.connectionsTo.push(connectedPost);
}
}
};

// create post8, post9, and post10
var post8 = Object.create(genericPost);
var post9 = Object.create(genericPost);
var post10 = Object.create(genericPost);

// assign property values and make connections
post8.x = 0;
post8.y = -3;
post8.postNum = 8;
post9.x = 6;
post9.y = 8;
post9.postNum = 9;
post10.x = -2;
post10.y = 3;
post10.postNum = 10;

post8.sendRopeTo(post10);
post9.sendRopeTo(post10);
post10.sendRopeTo(post8);
post10.sendRopeTo(post9);

post9.numBirds = 0;
post10.weathervane = "N";
post8.lightsOn = false;
post10.lightsOn = false;

* challenge 5.9

function Fencepost(x, y, postNum) {
this.x = x;
this.y = y;
this.postNum = postNum;
this.connectionsTo = [];
this.sendRopeTo = function(connectedPost) {
this.connectionsTo.push(connectedPost);
};
}

* challenge 5.10

function Fencepost(x, y, postNum) {
this.x = x;
this.y = y;
this.postNum = postNum;
this.connectionsTo = [];
this.sendRopeTo = function(connectedPost) {
this.connectionsTo.push(connectedPost);
};
}

// create post18, post19, and post20
var post18 = new Fencepost(-3, 4, 18);
var post19 = new Fencepost(5, -1, 19);
var post20 = new Fencepost(-2, 10, 20);

// establish post connections
post18.sendRopeTo(post20);
post20.sendRopeTo(post18);
post18.sendRopeTo(post19);
post19.sendRopeTo(post18);

* challenge 5.11

function Fencepost(x, y, postNum) {
this.x = x;
this.y = y;
this.postNum = postNum;
this.connectionsTo = [];
}

Fencepost.prototype() = {
sendRopeTo: function(connectedPost) {
this.connectionsTo.push(connectedPost);
},
removeRope: function(removeTo) {
var temp = [];
for (var i = 0; i < this.connectionsTo.length; i++) {
if (this.connectionsTo[i].postNum != removeTo) {
temp.push(this.connectionsTo[i]);
}
}
this.connectionsTo = temp;
},
movePost : function(x, y) {
this.x = x;
this.y = y;
}
};

* notes 5.12

PROPERTIES of THE OBJECT PROTOTYPE

.valueOf => returns data an type

(4 == "4") is true, because == does type conversion
(4 === "4") is false, because === does not do type conversion

OVERRIDING PROTOTYPAL PROPERTIES
myBox.prototype.valueOf = function() {
return this.width * this.height
}

.toString => returns string representation of a value
arrays will return string with values separated by commas

OVERRIDING
myBox.prototype.toString = function() {
return "Your box is named: "+this.name;
}

FINDING OBJECTS CONSTRUCTORS AND PROTOTYPE 13:00

.constructor
- returns original constructor function
.constructor.prototype
- returns prototype object of constructor function
can also be accessed with .__proto__

.hasOwnProperty
- searching prototype chains is a common task

* challenge 5.13

Fencepost.prototype.valueOf = function() {
return Math.sqrt((this.x * this.x) + (this.y * this.y));
}

* challenge 5.14

function Fencepost(x, y, postNum) {
this.x = x;
this.y = y;
this.postNum = postNum;
this.connectionsTo = [];
}

Fencepost.prototype = {
sendRopeTo: function(connectedPost) {
this.connectionsTo.push(connectedPost);
},
removeRope: function(removeTo) {
var temp = [];
for (var i = 0; i < this.connectionsTo.length; i++) {
if (this.connectionsTo[i].postNum != removeTo) {
temp.push(this.connectionsTo[i]);
}
}
this.connectionsTo = temp;
},
movePost: function(x, y) {
this.x = x;
this.y = y;
},
valueOf: function() {
return Math.sqrt(this.x * this.x +
this.y * this.y);
}
};

// override the toString method
Fencepost.prototype.toString = function() {
var list = "";
for (var i = 0; i < this.connectionsTo.length; i++) {
list += this.connectionsTo[i].postNum + "\n";
}
return "Fence post #" + this.postNum + ":\n" +
"Connected to posts:\n" + list +
"Distance from ranch: " + this.valueOf() + " yards";
};

AttachmentSize
codeschool notes.txt29.77 KB

Komentáře

Poslat nový komentář

  • Povolené HTML značky: <em> <strong>
  • Řádky a odstavce se zalomí automaticky.

Více informací o možnostech formátování

Image CAPTCHA
Enter the characters shown in the image.