clone

Name It…It’s Yours

In my previous post, I spoke about JavaScript objects. An object is simply a named collection of properties and methods. It can contain primitive data types, such as numbers, text and booleans. It can also contain complex data types, such as arrays, functions and even other objects.

So why mess with all of this object junk? Why not put everything in the global scope so you can access anything you want at any time? The answer is encapsulation. This is an object-oriented principle which speaks to the protection and organization of your data. If everything is in the global scope, everything is open for changing in your program and not logically organized. So you want as little global as possible. So objects give our data and program pieces more meaning and context.

JavaScript has its own built-in, standard objects, but you can also create your own custom objects. This is easily accomplished using constructors. A constructor is like a blueprint for an object. Its job is to establish properties and methods of an object. It can even set initial values of its properties. Here is an example…

Notice the “this” keyword. The “this” keyword allows us to refer to the context of properties. Basically, it means that the value of a property belongs to “this” constructor. For example, this.who is a property of “this” Invitation constructor.

Another thing to note is the capital “I”. In JavaScript, you typically begin with lowercase, but when it comes to constructors, you use uppercase. This is not strictly enforced, but is a standard convention.

So how do constructors help us? As I stated, they are blueprints to instantiate other objects. So we copy objects from objects. Here is an example using our Invitation constructor…

We now can access a new instance of the Invitation object with all of the new values we passed to it.

Happy Coding!

Clay Hess

Share this post