Showing posts with label objects II. Show all posts
Showing posts with label objects II. Show all posts
Thursday, April 25, 2013
Javascript: Objects II in Review
01/ 04
Instructions: Examine the languages object. Three properties are strings, whereas one is a number. Use a for-in loop to print out the three ways to say hello. In the loop, you should check to see if the property value is a string so you don't accidentally print a number.
HINT: Use an if statement in combination with the typeof operator to figure out whether or not something is a "string". If it's a "string", then print it!
Make sure you're checking the property value (e.g., "Hello!") and no the property name (e.g., english). Recall that if we save a property name to a variable, we can access the value associated with that name using bracket notation.
Recall the for-in loop:
for(var x in obj) {
executeSomething();
}
/* This will go through all properties of obj one by one and assign the property name on each run of the loop. */
var languages = {
english: "Hello!",
french: "Bonjour!",
notALanguage: 4,
spanish: "Hola!"
};
// print hello in the 3 different languages
for(var x in languages) {
if (typeof languages[x]);
}
}
02/ 04
Instructions: Add the sayHello method to the Dog class by extending its prototype. sayHello should print to the console: "Hello this is a [breed] dog", where [breed] is the dog's breed.
HINT: recall how we previously added a method to the Dog class:
Dog.prototype.bark = function()
{
console.log("Woof");
};
To access a dog's breed from within the method, use this.breed.
function Dog (breed) {
this.breed = breed;
};
// add the sayHello method to the Dog class
// so all dogs now can say hello
Dog.prototype.sayHello = function()
{
console.log("Hello this is a " + this.breed + " dog");
};
var yourDog = new Dog("golden retriever");
yourDog.sayHello();
var myDog = new Dog("dachshund");
myDog.sayHello();
03/ 04
Instructions: Let's first see what type Object.prototype is. Do this in line 2 and save it into prototypeType. If all goes well, you should realize that Object.prototype itself is an object! And since all objects have the hasOwnProperty method, it's pretty easy to check if hasOwnProperty comes from Object.prototype.
HINT: to see what type Object.prototype is, we should use typeof Object.prototype. The property we want to check for is actually "hasOwnProperty", so line 6 should look like: Object.prototype.hasOwnProperty("hasOwnProperty").
// what is this "Object.prototype" anyway...?
var prototypeType = typeof Object.prototype;
console.log(prototypeType);
// now let's examine it!
var hasOwn = Object.prototype.hasOwnProperty("hasOwnProperty");
console.log(hasOwn);
04/ 04
Instructions: Modify the StudentReport class so that no grades will be printed to the console in the for-in loop. However, getGPA should still function properly in the last line.
HINT: You should be changing public variables ( this.grade ) to private variables ( var grade ). If we want to getGPA to be able to be called from outside this class, should we change it to be private? You should find yourself needing to modify getGPA itself. this.grade1 will not be available if you did not declare it previously.
function StudentReport() {
var grade1 = 4;
var grade2 = 2;
var grade3 = 1;
this.getGPA = function() {
return ( grade1 + grade2 + grade3 ) / 3;
};
}
var myStudentReport = new StudentReport();
for(var x in myStudentReport) {
if(typeof myStudentReport[x] !== "function") {
console.log("Muahaha! "+myStudentReport[x]);
}
}
console.log("Your overall GPA is "+myStudentReport.getGPA());
Labels:
codeacademy,
coding,
CS,
javascript,
objects II,
programming,
review
Tuesday, April 23, 2013
Javascript: Private and Public
All properties in JavaScript are automatically public, which means that they can be accessed outside of the class. Look at the Person class below. It has three properties: firstName, lastName, and age. Think of these properties as the information a class is willing to share.
On lines 8 and 9, we access the firstName and lastName properties of john and assign them myFirst and myLast. Note that we are free to access the firstName, lastName, and age properties, which is what we mean when we say that they are public.
function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
var john = new Person( 'John', 'Doe', 30);
var myFirst = john.firstName;
var myLast = john.lastName;
var myAge = john.age;
Yay! But what if an object wants to keep some information hidden? Remember local variables? (--They can only be accessed from within that function!) Well functions can also have private variables which are pieces of information that can only be directly accessed from within the class.
Here, the Person class has been modified to have a private variable called bankBalance. Notice that it looks just like a normal variable except that it is defined inside the constructor for Person, without using this, but instead using var. This makes bankBalance a private variable.
function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
var bankBalance = 7500;
}
We we try to print his bankBalance out, all we get is undefined.
Methods can also be private within a class and inaccessible outside of the class. Changing this.returnBalance from the last exercise to var returnBalance makes this method private. The way to access a private method is similar to accessing a private variable. You must create a public method for the class that returns the private method.
var returnBalance = function() {
return bankBalance;
};
this.askTeller = function() {
return returnBalance;
};
var john = new Person('John', 'Doe', 30);
console.log(john.returnBalance);
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);
The askTeller function has been modified within the Person class to directly give you your balance. However, it now needs the account password parameter in order to return the bankBalance.
function Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;
this.askTeller = function(pass) {
if (pass == 1234) {
return bankBalance;
}
else {
return "Wrong password.";
}
};
var myBalance = function(pass) {
return askTeller;
};
}
var john = new Person('John','Doe',30);
/* the variable myBalance should access askTeller() with a password as an argument */
Labels:
coding,
CS,
javascript,
objects II,
private,
programming,
public
Saturday, April 20, 2013
Javascript: Object-Oriented Programming Basics
Alright, so now we can finally learn the basics of OOP! The first thing I'm going to introduce is a class. When you make a constructor, you are actually defining a new class! A class can be thought of as a type, or a category of objects -- remember numbers and strings? Those are types too!
/* take a look at the example below, jenny and alex are two separate objects, but they both belong to the class Person */
function Person(name, age) {
this.name = name;
this.age = age;
};
var jenny = new Person("Jenny", 18);
var alex = new Person("Alex", 13);
A prototype keeps track of what a given class can or cannot do. Javascript automatically defines the prototype for class with a constructor.
// for example, this dog constructor ensures that the dog prototype has a breed property
function Dog (breed) {
this.breed = breed;
};
Classes are really useful because they tell us helpful information about objects. You can actually think of an object as a particular instance of a class. Look at our Person class. We know that any Person will have a name and age because they are in they are in the constructor. Let's create a function like printPersonName--this will take a Person as an argument and print out their name.
// recall our Person class
function Person(name, age) {
this.name = name;
this.age = age;
};
// a function that prints out the name of any given person
function printPersonName(p) {
console.log(p.name);
};
var jenny = new Person("Jenny", 18);
printPersonName(jenny);
If you want to add a method to a class such that all members of the class can use it, we use the following syntax to extend the prototype:
className.prototype.newMethod =
function() {
statements;
};
// here's another example using the dog class:
function Dog (breed) {
this.breed = breed;
};
// here we make fifi and teach her how to bark
var fifi = new Dog("pomeranian");
Dog.prototype.bark = function() {
console.log("Arf!");
};
fifi.bark();
// here we make maya
var maya = new Dog("Pug");
maya.bark();
P.S. I created a youtube channel where I'll be uploading vlogs and cooking videos and random miscellaneous things, so if you want to get to know me a little better, I suggest you check it out! (And subscribe!) :)
Labels:
basics,
classes,
codeacademy,
coding,
CS,
fifi,
javascript,
JS,
maya,
objects II,
OOP,
pom,
programming,
prototypes,
pug
Friday, April 19, 2013
Javascript: Intro to Objects II
I know we've been reviewing objects I again and again these past couple of blog posts, but I think it's safe to say that there's a reason for this perpetual repetition. Codeacademy really wants you to get down the basics before moving into new territories. Last night I attempted to finish the entire course in one-go--and was almost successful in that endeavor. However, I was stumped by the last lesson... probably because my level of understanding was just sufficient in order for me to complete the problems right in front of me, but not enough to truly understand and apply what I had just learned to more complex situations. Oh well. Hopefully after updating this blog with the lessons I covered last night, I'll be somewhat more refreshed (and a gain deeper understanding)!
// literal notation creates a single object
var jenny = {
job: "student",
married: false
};
// constructor notation involves defining an object constructor using the function keyword
function Person(job, married) {
this.job = job;
this. married = married;
}
// create a "jenny" object using the Person constructor
var jenny = new Person("student", false);
Methods are essentially functions associated with objects, remember?
function someObj() {
this.someMethod = function() {
};
}
// add a speak method to the Person constructor via constructor notation
function Person(job, married) {
this.job = job;
this.married = married;
this.speak = "Hello!"
}
// add method to object via literal notation
var jenny = {
job: "student",
married: false,
speak: function(mood) {
console.log("Hello, I am feeling " + mood);
};
jenny.speak("fantastic");
jenny.speak("meh");
When defining a method for an object, use this.propertyName to reference other properties in that object. When that method is called, this.propertyName will always refer to the most recent value of propertyName.
var jenny = {
job: "student",
married: false,
sayJob: function() {
console.log("Hi, I work as a " + this.job);
}
};
// jenny's first job
jenny.sayJob();
// change jenny's job to "coding wizard with big fluttery beard"
jenny.job = "coding wizard with big fluttery beard";
//jenny's second job:
jenny.sayJob();
Throughout this post, I've been using dot notation to get the value of an object's property:
someObj.propName
However, we can also use bracket notation:
someObj["propName"]
The advantage of using bracket notation is that we aren't restricted to using only strings in the brackets. We can also use variables whose values are property names:
var someObj = {propName: someValue};
var myProperty = "propName";
someObj[myProperty]
// some Obj[myProperty] = someObj["propName"]
/* first set aProperty to a string of the first property in jenny (ie. the job property), then print jenny's job using bracket notation and a property */
var aProperty = "job";
console.log(jenny[aProperty];
);
Labels:
coding,
CS,
intro,
javascript,
JS,
objects I,
objects II,
programming,
review
Subscribe to:
Posts (Atom)