JavaScript for WordPress Developers: Getting Started With Objects

Tutorials

What exactly are JavaScript objects? Learn what they are and how to use them in this four-part series about the world of JavaScript and what it means for working with WordPress.

JavaScript objects and functions

Objects are one of the most important and most powerful features of JavaScript and many built-in features use objects natively.

Essentially, an object is a collection of properties, and a property consists of a key and a value. In this sense, objects in JavaScript are akin to associative arrays in PHP but the similarities end there.

This is the second post in our five-part series focusing on JavaScript for WordPress developers. Throughout this series, you’ll learn the basics but I’ll presume you already have a working knowledge of HTML and CSS. If you need help with these building blocks, take a look at our series about WordPress Development for Beginners.

In the last article in this series, we looked at the very basics of JavaScript – how to add to a page and use variables and functions. In this tutorial, we’ll focus on commonly used objects in JavaScript.

Missed a tutorial in our JavaScript for WordPress Developers series? You can catch up on all five posts here:

Objects

Let’s dive straight in by looking at an example of an object in JavaScript:

Loading gist 14d10078f56f356fc5dcdd2462acaf27

This is a very simple object with four properties. The first property has the key “name” and the value “Daniel Pataki.” As you can see from the other properties, values may use many different data types.

What makes objects so useful, but also a little confusing, is that property values can also be functions. If you’ve copy-pasted some jQuery code before you may have seen this in action in the form of callback functions, which looks something like this:

Loading gist 268cd6e22df7155da58916733ef18b0a

The code above would send a post request to the given URL. The “complete” property invokes a function, which is run when the request has been completed. To see how this would work let’s quickly write a function of our own:

Loading gist bbb3363642bf505907536443e17cad4d

The object contains a name property and a greeting property, which is a function. Once defined we can invoke that function using the dot syntax: me.greeting. You can even reference properties from within the same object using the this keyword.

If you’ve worked with PHP objects before the idea is very similar. The simplicity of the syntax throws people sometimes, but there is tremendous power within.

Working With Objects

Let’s take a step back and learn how to create and manipulate objects. An object is always encased in curly braces. Property names can be unquoted but must be quoted if they contain special characters like dashes. Property values can be of multiple types including strings, integers, arrays and other objects.

Let’s create a test object with some useful information we can manipulate:

Loading gist c7476ed2824c5f2401eadfc7037e448f

To get the value of a property you can use the dot notation or the square bracket notation. The bracket notation is useful if you want to use a variable property name. Take a look at the example below:

Loading gist 75a30c3ec15e256e0aaaed430c868318

And here’s what it looks like in the browser console:

Logging object values
Logging object values

You can use a function contained within an object similarly, just add a parenthesis at the end (and parameters if needed).

Loading gist d9e03895545b1c9418677f63b1971033

The function calculates reading time by presuming a reading speed of 2.5 minutes per page. I multiplied the total page count by 2.5 to arrive at the number of minutes required for a complete read through. I then divide by 60 to arrive at the number of hours needed.

In the previous article, we created an example where we listed some tweets using an array, but we can make our example a lot more flexible using objects. Here’s the complete code re-written to use objects:

Loading gist 3eac71488952c4a96b59e9b4df789a50

The biggest change you’ll see is that instead an array of tweets and a username given separately, I’ve created an array of tweet objects. Each tweet object contains the tweet and the username. This removes the uncertainty of passing in the username from somewhere else.

The tweet() function now uses the object’s properties instead of separate arguments and I’ve removed document.write to make sure it just returns a string, which can then be used anywhere.

Using Constructors

Currently, our code is not bad but it could still be a lot better. We will probably never need to display a tweet without a tweet object, so we shouldn’t really define our tweet function outside of the object. If we use the same structure we would need to add a display_tweet() function into all three objects.

This is where constructors come in. If you’re familiar with object-oriented PHP this is similar to using classes and objects in PHP. Think of a constructor as a way to initialize a class. Let me show you some code to make this clearer:

Loading gist 4c890d81ca974f63ac87123292ee9966

Let’s start with tweet_1. I used new Tweet() to call the Tweet function, passing in two parameters. The function is a constructor that creates properties for the object dynamically. It assigns the first parameter to this.text and the second to this.username. It also creates a this.display function that displays the tweet.

Within the function we can refer to properties using the this keyword. Outside of the function we use the dot notation. To log the first tweet’s text we use tweet_1.text, to log the tweet display for the second one we use tweet_2.display().

The beauty of this is its reusability. You can create as many tweets you like by creating a new object using the Tweet class. The object will contain all the functions and other elements it needs to function.

Let’s rewrite our tweet example with constructors in mind:

Loading gist 9ac6c39ab12b04a4130532a6909a66e3

That’s a lot cleaner and a lot more understandable. I’ve added the ability to add a prefix and a suffix to the tweet to give it some extra flexibility. This way we can display it as a list element easily.

Overview

In this tutorial, we delved into JavaScript objects and learned how they can be used to create data structures to make our code neater, better to understand and more flexible. Along with the previous tutorial you should now be up to speed on arrays, variables and basic JavaScript.

In the next tutorial, we’ll take a look at jQuery, the JavaScript framework used heavily by WordPress. You’ll learn how to manipulate websites so you can create great things like toggle sections, date drop-downs and more.

All the good WordPress stuff, once every two weeks

Subscribe

Leave a comment