Friday, April 19, 2013

Javascript: Even More on Objects




















How do we figure out if something is an object? We can call typeof thing to figure this out. In general, most types fall under "number", "string", "function", and "object".
var someObject = {someProperty: someValue};
console.log( typeof someObject ); 

// concrete example
var anObj = { job: "I'm an object!" };
console.log( typeof anObj );

Every object in JS comes with some baggage, including a method called hasOwnProperty. This lets us know if an object has a particular property.
// this is how you use hasOwnProperty
var myObj = {
    name: myObj
};

console.log( myObj. hasOwnProperty('name')); // should print true

console.log( myObj. hasOwnProperty('nickname')); // should print false

// here's another example of hasOwnProperty used in an if-else statement: 

/* recall if-else statements: 
if ( expression ) {
} else {
} */

var suitcase = {
    shirt: "Hawaiian"
}; 

if (suitcase.hasOwnProperty("shorts")) {
    console.log(suitcase.shorts); 
} else {
    suitcase.shorts = "red"; 
    console.log(suitcase.shorts);
}

To work with all the properties that belong to an object, let's bring back the for-in loop. 

// define some object 
var pom = {
species: "pomeranian", 
age: 10, 
color: "golden",
};

// for-in loop to print out pom's property names 
for(var property in pom) {
console.log(property); 

We've just learned how to print all of an object's property names with a for-in loop, but how do we print out the values associated with every property?

// for-in loop to print out the value of all pom's properties 

// recall 
pom.species = pom["species"] = "pomeranian" 
// if we say
var x = "species" 
// then
dog[x] = "pomeranian'

for(var x in pom) {
console.log(pom [x]); 

No comments:

Post a Comment