[JavaScript] Introduction to Objects II
Objects, Objects Everywhere
// complete these definitions so that they will have
// the appropriate types
var anObj = { job: "I'm an object!" };
var aNumber = 42;
var aString = "I'm a string!";
console.log(typeof(anObj)); // should print "object"
console.log(typeof(aNumber)); // should print "number"
console.log(typeof(aString)); // should print "string"
var myObj = {
// finish myObj
name: "Morris",
};
console.log( myObj.hasOwnProperty('name') ); // should print true
console.log( myObj.hasOwnProperty('nickname') ); // should print false
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5
};
for(var property in nyc) {
console.log(property);
}
// write your for-in loop here
You Down With OOP?
function Dog (breed) {
this.breed = breed;
};
// here we make buddy and teach him how to bark
var buddy = new Dog("golden Retriever");
Dog.prototype.bark = function() {
console.log("Woof");
};
buddy.bark();
// here we make snoopy
var snoopy = new Dog("Beagle");
/// this time it works!
snoopy.bark();
function Cat(name, breed) {
this.name = name;
this.breed = breed;
}
// let's make some cats!
var cheshire = new Cat("Cheshire Cat", "British Shorthair");
var gary = new Cat("Gary", "Domestic Shorthair");
// add a method "meow" to the Cat class that will allow
Cat.prototype.meow = function() {
console.log("Meow!");
}
// all cats to print "Meow!" to the console
cheshire.meow();
gary.meow();
// add code here to make the cats meow!
Inheriting a Fortune
// create your Animal class here
function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}
// create the sayName method for Animal
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
}
function Penguin(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}
Penguin.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
}
// provided code to test above constructor and method
var penguin = new Penguin("Captain Cook", 2);
penguin.sayName();
function Penguin(name) {
this.name = name;
this.numLegs = 2;
}
// create your Emperor class here and make it inherit from Penguin
function Emperor(name) {
this.name = name;
}
Emperor.prototype = new Penguin();
// create an "emperor" object and print the number of legs it has
var emperor = new Emperor("ee");
console.log(emperor.numLegs);