Javascript Generic Object

Object property values in Javascript generic object

Many Javascript experts caution against using global variables in code. With multiple libraries being used, it’s way too easy to cause a collision between variables of the same name from different contexts. Simply, if your code has a variable called playerScore, and code you import has a variable of the same name, you’re in for trouble. The antidote for global variables in Javascript is the Javascript generic object.

A generic object is essentially an empty blueprint for an object. You can define it anywhere in your Javascript code. There are a couple of ways to define the object. This is my favorite:

In the example above, we’re defining an object called position. We start by using the keyword new and instantiating position as an object. Once we’ve instantiated our object we’re able to create properties of the object. Note that the properties can be strings, floating point numbers integers or a combination of the types.

When referencing the objects and properties elsewhere in the code we use the same dot notation that we used when defining the objects.

The code above would yield the following in Chrome Developer Tools’ logging system:

Object property values in Javascript generic object

A second implementation of Javascript objects allows you to create multiple instances of the object itself. Examine the following code snippet:

We’ve created a generic blueprint for an object known as Employee here. We haven’t actually created any instances of employee. In the first example, we created a position object and instantiated it right away. In this example, we’ll create instances of employee like this:

Note that the Employee object we created earlier acts as a constructor and assigns the values that are passed to it to the respective properties. Accessing the values here uses the same dot notation discussed before, for example, .

As your Javascript code gets more complex, Javascript Generic Objects will become more and more useful as an organizing structure for your applications.

About the author
Mark Lassoff has taught over 250,000 students how to code online, and in person. He’s a popular author and speaker on programming and has appeared at TechWeek, SXSW, CodePoLousa and DevCon. His expertise is in web and mobile development. Mark lives in Connecticut.

1 Comment

Leave a Reply

Your email address will not be published.