{"id":157010,"date":"2016-07-26T14:00:42","date_gmt":"2016-07-26T14:00:42","guid":{"rendered":"https:\/\/premium.wpmudev.org\/blog\/?p=157010"},"modified":"2016-10-05T06:01:44","modified_gmt":"2016-10-05T06:01:44","slug":"javascript-wordpress-objects","status":"publish","type":"post","link":"https:\/\/wpmudev.com\/blog\/javascript-wordpress-objects\/","title":{"rendered":"JavaScript for WordPress Developers: Getting Started With Objects"},"content":{"rendered":"<p>Objects are one of the most important and most powerful features of JavaScript and many built-in features use objects natively.<\/p>\n<p>Essentially, an\u00a0object 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.<\/p>\n<p>This is the second post in our five-part series focusing on JavaScript for WordPress developers.\u00a0Throughout this series, you\u2019ll learn the basics but I\u2019ll 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 <a href=\"https:\/\/wpmudev.com\/blog\/wordpress-development-beginners-getting-started\/\" target=\"_blank\">WordPress Development for Beginners<\/a>.<\/p>\n<p>In the last article in this series, we looked at <a href=\"https:\/\/wpmudev.com\/blog\/javascript-wordpress-basics\/\" target=\"_blank\">the very basics of JavaScript<\/a> \u2013 how to add to a page and use variables and functions. In this tutorial, we&#8217;ll focus on commonly used objects\u00a0in JavaScript.<\/p>\n<p><strong>Missed a tutorial in our JavaScript for WordPress Developers series? You can catch up on all five posts here:<\/strong><\/p>\n<ul>\n<li><a href=\"https:\/\/wpmudev.com\/blog\/javascript-wordpress-basics\/\" target=\"_blank\">JavaScript for WordPress Developers: Learning the Basics<\/a><\/li>\n<li><a href=\"https:\/\/wpmudev.com\/blog\/javascript-wordpress-objects\/\" target=\"_blank\">JavaScript for WordPress Developers: Getting Started With Objects<\/a><\/li>\n<li><a href=\"https:\/\/wpmudev.com\/blog\/getting-started-jquery\/\" target=\"_blank\">JavaScript for WordPress Developers: Getting Started With jQuery<\/a><\/li>\n<li><a href=\"https:\/\/wpmudev.com\/blog\/loading-javascript-wordpress\/\" target=\"_blank\">JavaScript for WordPress Developers: Loading JavaScript in WordPress<\/a><\/li>\n<li><a href=\"https:\/\/wpmudev.com\/blog\/javascript-ajax\/\" target=\"_blank\">Javascript For WordPress Developers: Using AJAX<\/a><\/li>\n<\/ul>\n<h3>Objects<\/h3>\n<p>Let&#8217;s dive straight in by looking at an example of an object in JavaScript:<\/p>\n<div class=\"gist\" data-gist=\"14d10078f56f356fc5dcdd2462acaf27\" data-gist-file=\"first-object.js\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/14d10078f56f356fc5dcdd2462acaf27.js?file=first-object.js\">Loading gist 14d10078f56f356fc5dcdd2462acaf27<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>This is a very simple object with four properties. The first property has the key &#8220;name&#8221; and the value &#8220;Daniel Pataki.&#8221; As you can see from the other properties, values may use many different data types.<\/p>\n<p>What makes objects so useful, but also a little confusing, is that property values can also be functions. If you&#8217;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:<\/p>\n<div class=\"gist\" data-gist=\"268cd6e22df7155da58916733ef18b0a\" data-gist-file=\"object-with-function.js\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/268cd6e22df7155da58916733ef18b0a.js?file=object-with-function.js\">Loading gist 268cd6e22df7155da58916733ef18b0a<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>The code above would send a post request to the given URL. The &#8220;complete&#8221; property invokes a function, which is run when the request has been completed. To see how this would work let&#8217;s quickly write a function of our own:<\/p>\n<div class=\"gist\" data-gist=\"bbb3363642bf505907536443e17cad4d\" data-gist-file=\"function-call.js\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/bbb3363642bf505907536443e17cad4d.js?file=function-call.js\">Loading gist bbb3363642bf505907536443e17cad4d<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>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: <code>me.greeting<\/code>. You can even reference properties from within the same object using the <code>this<\/code> keyword.<\/p>\n<p>If you&#8217;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.<\/p>\n<h3>Working With Objects<\/h3>\n<p>Let&#8217;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.<\/p>\n<p>Let&#8217;s create a test object with some useful information we can manipulate:<\/p>\n<div class=\"gist\" data-gist=\"c7476ed2824c5f2401eadfc7037e448f\" data-gist-file=\"object.js\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/c7476ed2824c5f2401eadfc7037e448f.js?file=object.js\">Loading gist c7476ed2824c5f2401eadfc7037e448f<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>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:<\/p>\n<div class=\"gist\" data-gist=\"75a30c3ec15e256e0aaaed430c868318\" data-gist-file=\"retrieve-value.js\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/75a30c3ec15e256e0aaaed430c868318.js?file=retrieve-value.js\">Loading gist 75a30c3ec15e256e0aaaed430c868318<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>And here&#8217;s what it looks like in the browser console:<\/p>\n<figure class=\"wp-caption aligncenter\" data-caption=\"true\"><img loading=\"lazy\" decoding=\"async\" class=\"attachment-735x735 size-735x735\" src=\"https:\/\/wpmudev.com\/blog\/wp-content\/uploads\/2016\/07\/logging-the-object.png\" alt=\"Logging object values\" width=\"735\" height=\"258\" \/><figcaption class=\"wp-caption-text\">Logging object values<\/figcaption><\/figure>\n<p>You can use a function contained within an object similarly, just add a parenthesis at the end (and parameters if needed).<\/p>\n<div class=\"gist\" data-gist=\"d9e03895545b1c9418677f63b1971033\" data-gist-file=\"object-functions.js\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/d9e03895545b1c9418677f63b1971033.js?file=object-functions.js\">Loading gist d9e03895545b1c9418677f63b1971033<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>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.<\/p>\n<p>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&#8217;s the complete code re-written to use objects:<\/p>\n<div class=\"gist\" data-gist=\"3eac71488952c4a96b59e9b4df789a50\" data-gist-file=\"tweets-object1.js\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/3eac71488952c4a96b59e9b4df789a50.js?file=tweets-object1.js\">Loading gist 3eac71488952c4a96b59e9b4df789a50<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>The biggest change you&#8217;ll see is that instead an array of tweets and a username given separately, I&#8217;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.<\/p>\n<p>The <code>tweet()<\/code> function now uses the object&#8217;s properties instead of separate arguments and I&#8217;ve removed <code>document.write<\/code> to make sure it just returns a string, which can then be used anywhere.<\/p>\n\n<h3>Using Constructors<\/h3>\n<p>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&#8217;t really define our <code>tweet<\/code> function outside of the object. If we use the same structure we would need to add a <code>display_tweet()<\/code> function into all three objects.<\/p>\n<p>This is where constructors come in. If you&#8217;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:<\/p>\n<div class=\"gist\" data-gist=\"4c890d81ca974f63ac87123292ee9966\" data-gist-file=\"constructor.js\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/4c890d81ca974f63ac87123292ee9966.js?file=constructor.js\">Loading gist 4c890d81ca974f63ac87123292ee9966<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>Let&#8217;s start with <code>tweet_1<\/code>. I used <code>new Tweet()<\/code> to call the <code>Tweet<\/code> function, passing in two parameters. The function is a constructor that creates properties for the object dynamically. It assigns the first parameter to <code>this.text<\/code> and the second to <code>this.username<\/code>. It also creates a <code>this.display<\/code> function that displays the tweet.<\/p>\n<p>Within the function we can refer to properties using the <code>this<\/code> keyword. Outside of the function we use the dot notation. To log the first tweet&#8217;s text we use <code>tweet_1.text<\/code>, to log the tweet display for the second one we use <code>tweet_2.display()<\/code>.<\/p>\n<p>The beauty of this is its reusability. You can create as many tweets you like by creating a new object using the <code>Tweet<\/code> class. The object will contain all the functions and other elements it needs to function.<\/p>\n<p>Let&#8217;s rewrite our tweet example with constructors in mind:<\/p>\n<div class=\"gist\" data-gist=\"9ac6c39ab12b04a4130532a6909a66e3\" data-gist-file=\"tweets-object2.js\"><a class=\"loading\" href=\"https:\/\/gist.github.com\/9ac6c39ab12b04a4130532a6909a66e3.js?file=tweets-object2.js\">Loading gist 9ac6c39ab12b04a4130532a6909a66e3<\/a><div class=\"gist-consent-notice\" style=\"display:none\"><p>Please <a href=\"javascript:Cookiebot.renew()\">update your cookie preferences<\/a> to enable preference cookies to view this gist.<\/p><\/div><\/div>\n<p>That&#8217;s a lot cleaner and a lot more understandable. I&#8217;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.<\/p>\n<h3>Overview<\/h3>\n<p>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.<\/p>\n<p>In the next tutorial, we&#8217;ll take a look at jQuery, the JavaScript framework used heavily by WordPress. You&#8217;ll learn how to manipulate websites so you can create great things like toggle sections, date drop-downs and more.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Objects are one of the most important and most powerful features of JavaScript and many built-in features use objects natively. Essentially, an\u00a0object 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. [&hellip;]<\/p>\n","protected":false},"author":344049,"featured_media":157786,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"blog_reading_time":"","wds_primary_category":0,"wds_primary_tutorials_categories":0,"footnotes":""},"categories":[263],"tags":[505],"tutorials_categories":[],"class_list":["post-157010","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tutorials","tag-javascript"],"_links":{"self":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts\/157010","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/users\/344049"}],"replies":[{"embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/comments?post=157010"}],"version-history":[{"count":11,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts\/157010\/revisions"}],"predecessor-version":[{"id":159773,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/posts\/157010\/revisions\/159773"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/media\/157786"}],"wp:attachment":[{"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/media?parent=157010"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/categories?post=157010"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/tags?post=157010"},{"taxonomy":"tutorials_categories","embeddable":true,"href":"https:\/\/wpmudev.com\/blog\/wp-json\/wp\/v2\/tutorials_categories?post=157010"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}