-
Notifications
You must be signed in to change notification settings - Fork 4
Objects
I have a particular foundness for objects...
Firstly, when writing programs in JavaScript, it's helpful to remember that in many objected oriented or prototype based programming languages, as JavaScript is, essentially, everything is an object.
Everything is an object, even the built-in datatypes, and the more detailed or specialized it needs to be, the more we describe it to the runtime. Objects are basically comprised of two things:
- Properties: What the object has, or another way to look at it, it's parts (A car has an engine, wheels, battery, etc). Properties are essentially variables (or constants - values that cannot change).
- Behaviours: What the object can do (A car can go, stop, turn, etc). Behaviours are essentially functions or otherwise known as methods.
In JavaScript, the simplest Object is, interestingly, an Object! Think of an object as a piece of clay that you can shape into anything. So when you literally create one, it can be blank, empty, and you fill it or shape it as you need, defining what it's made of and what it can do.
To create one, you can simple do:
var myObject = {};
Here, we are assigning to the variable myObject
an empty Object. Objects are literally represented with the curly brackets {}
, otherwise known as braces. So when we use = {}
, we're saying, equals an empty Object. This is called an Object literal, and I like to think it's because this is literally how you make an Object.
var person = {};
console.log(person); // prints {}
Terrific, we have a person Object ...but ...wait, the person is blank! You can see when we logged the person Object using console.log(person);
, we were given {}
, literally a blank, empty Object!
Objects store their values by a String key, the key being the name of the property, and we can use that key to look up the value of property. The literal syntax for creating properties on an Object looks like this:
var myObject = {id: 1,
name: "Some Object"};
console.log(myObject.id) // prints 1;
console.log(myObject.name) // prints Some Object;
Let's give our person a bit of a personality:
person.firstName = "Jack";
person.lastName = "Jones";
console.log("First Name: " + person.firstName); // prints First Name: Jack
console.log("Last Name: " + person.lastName); // prints Last Name: Jones
Cool, because Objects are dynamic, as a opposed to static, they can be altered at runtime, and in the above example, we're using dot notation or dot syntax to create properties on our person Object. We're really saying, 'On the person variable, add or overwrite a property called nameFirst, and assign the String "Jack" to it'. So, after this point, we can execute console.log(person.firstName);
, which prints Jack
.
So, because the keys of an Object are actually Strings, we can also use the syntax myObject["type"] = "Awesome Object";
to create properties, sometimes called Array syntax. Go ahead and add a city property to our person:
person["city"] = "New Orleans";
console.log("City: " + person.city); // prints City: New Orleans
Sweet, now we're cooking!
Okay, so we've given our person a bit more of a personality in that we've added some properties to the person Object. What about behaviours? Remember we said Objects are made of properties and behaviours. Here we come to functions, or otherwise known as in the object oriented world, methods.
Functions are a group of statements executed one after another within their own sort of subprogram or closed environment - called a closure - think of them like a program wihtin a program. And we can store them in memory by assinging them to a variable or constant so that we can run them again and again. This helps with maintainability, but because they kind of have their own private world when they execute, they are extremely powerful. Instead of passing around a value, we can pass around a whole set of instructions that perform all kinds of calculations and retrieval of data!
Object oriented programming tries to model objects in a system like objects in the real world. So, a car has wheels and an engine, that is, properties, and methods by which we can start it, steer it, and stop it - hopefully! We know what properties are, methods are merely functions we attach to objects to act as methods or behaviours of the object - and here's a tip, methods are most often named using a verb:
person.sayHello = function() {
console.log("Hello, my name is " + this.firstName + " " + this.lastName + ", I live in " + this.city);
}
person.sayHello(); // prints Hello, my name is Jack Jones, I live in New Orleans
Above, we're assigning a property to our person object that is a function. The function declaration has the syntax function(arg, ...args) { // body };
. We execute the function, that is, make it run, by stating it's name, followed by parenthesis ()
. The body of the function resides between the two curly brackets (yes, besides representing an Object, in the context of a function declaration, the curly brackets represent the body of the function).
There's a couple of important things to note here:
- The keyword this: The
this
keyword is a very important concept, and it usually refers to the Object within who's scope you are presently, at runtime - but in the case of a function body, it depends on how the function was invoked - but we'll cover this context a bit later, hahaha! You can think ifthis
like saying, "who's house am I in?" - that will tell you whose properties are about you! So in the above example, thethis
in the expressionthis.firstName
refers to our person object. - In this example, we're also introducing what's called String concatenation to glue parts of many strings together into one String to print something more meaningful. We're using the plus operator,
+
, to concatenate the various strings, for example"Hello, my name is " + this.firstName
, etc. Here's the full line, and you'll notice we're concatenating 6 strings, including the space,' '
.
"Hello, my name is " + this.firstName + " " + this.lastName + ", I live in " + this.city
- Finally, we are invoking, or calling or executing, our new function, the method
sayHello
, by the statementperson.sayHello();
. Addressing the function name, in this case,sayHello
on theperson
Object, followed immediately by the open and close parenthesis, we execute the function. We're really saying, "On the person object, find the sayHello method and execute it". In fact, dig this, we've been executing functions since the second line of this app:console.log('This is a function call!');
is a call to thelog
function on theconsole
Object!
Excellent, our call to person.sayHello();
printed "Hello, my name is Jack Jones, I live in New Orleans"!
© 2014-2015 Operation Spark