
Objects in JavaScript are a lot like hashes in Ruby. They store information using keys and values.
Here is an object in JavaScript:
var cafe = {
name: "La Colombe",
location: "New York City"
}
Here is a hash in Ruby:
school = {
"name" => "Flatiron",
"location" => "Brooklyn"
}
The way that you would access the values are even very similar.
Here is how you would access a value in JavaScript:
cafe.name;
Here is how you would access a value in Ruby:
school["name"]
Both will give you the values associated with those keys. Let’s add some more information to our JavaScript object:
cafe.food = "sandwiches";
This would add a key of “food” and a value of “sandwiches” to our cafe object.
What if we wanted to create objects for a lot of different cafes in JavaScript? That would be a lot of writing and not very DRY (don’t repeat yourself). When you know that you are going to be creating a lot of objects that will have the same attributes you should use a constructor function. Here is an example of what a constructor function looks like:
function Cafe(name, location){
this.name = name;
this.location = location;
}
In the code above we have the following:
- “function” – This is a JavaScript keyword identifying the rest of the code as a function.
- “Cafe” – The name of our function and since this is uppercase we know that this is specifically a constructor function.
- (name, location) – These are arguments to the function. You can think of these as place holders for when you pass in the actual names for the instance you are creating.
- {} – These will hold all the code for the function.
- “this.name = name;” – The word “this” is a keyword in JavaScript. When you create an instance of the function “this” it is going to refer to that particular instance. You are then setting “this.name” to “name” which is going to be the value of what you pass into the function.
Here is how you would create a new Cafe instance:
var fresco = new Cafe("Fresco", "2nd Avenue");
The result of above will create a fresco object. To see the new object you created you can type:
console.log(fresco);
The above will print to the screen:
{name: "Fresco",
location: "2nd Avenue"
}
If you had to create a lot of cafes this would save you a lot of time!