Thursday, April 18, 2013

Javascript: Objects in Review


Objects give us a way to represent things--IRL or virtual. We're able to do this by storing information within the object's properties.

So far, we have learned two ways to make objects:
// literal notation, where we use var Name = { }; 
var cutedork = {
    age: 18,
    country: "United States"
};

// constructor notation, where we use the keyword new
var cutedork2 = new Object(); 
    cutedork2.age = 18;
    cutedork2.country = "United States";

Remember what properties are? They're similar to variables... except that they belong to an object and hold information. We can access properties in two ways:

// dot notation, with ObjectName.PropertyName
var age = jenny.ages

// bracket notation, with ObjectName["PropertyName"] (--don't forget the quotes!)
var country = jenny['country']

Methods act like functions associated with an object and they're especially useful when you ether want to:
1. Update the object properties
2. Calculate something based on an object's properties

// example of defining area and perimeter methods
function Circle (radius) {
    this.radius = radius;
    this.area = function () {
        return Math.PI * this.radius * this.radius;
    };

function Perimeter (radius) {
    this.radius = radius;
    this.area = function() {
        return 2 * Math.PI * this.radius;
    };
}}

Lastly--in addition to our basic object constructor, we can create our own custom constructors which are helpful for two reasons:
1. We can assign our object properties through parameters we pass in when the object is created.
2. We can give our object methods automatically.

// 3 lines are required to make mdfrmscrtch
var mdfrmscrtch = new Object(); 
mdfrmscrtch.blogURL = "http://mdrmscrtch.blogspot.com";
mdfrmscrtch.creator = "Jenny"

// A custom constructor for blog
function Blog (blogURL, creator) {
    this.blogURL = blogURL;
    this.creator = creator;
}

// Use this new creator to make hello_cutedork in one line!
var hello_cutedork = new Blog("http://hellocutedork.blogspot.com", "Jenny");

Song of the day // Lucky Ones (Lana Del Rey)

No comments:

Post a Comment