{"id":9231,"date":"2016-07-27T02:03:24","date_gmt":"2016-07-27T06:03:24","guid":{"rendered":"http:\/\/byteplate.com\/uncategorized\/javascript-for-wordpress-developers-getting-started-with-objects\/"},"modified":"2016-07-27T02:03:37","modified_gmt":"2016-07-27T06:03:37","slug":"javascript-for-wordpress-developers-getting-started-with-objects","status":"publish","type":"post","link":"https:\/\/byteplate.com\/wpmu-dev\/javascript-for-wordpress-developers-getting-started-with-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 four-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:\/\/premium.wpmudev.org\/blog\/wordpress-development-beginners-getting-started\/\">WordPress Development for Beginners<\/a>.<\/p>\n<p>In the last article in this series, we looked at <a href=\"https:\/\/premium.wpmudev.org\/blog\/javascript-wordpress-basics\/\">the very basics of JavaScript<\/a> \u2013 how to add to a page and use variables and functions. In this tutorial, we\u2019ll focus on commonly used objects\u00a0in JavaScript.<\/p>\n<p><span id=\"more-157010\"><\/span><\/p>\n<h3>Objects<\/h3>\n<p>Let\u2019s dive straight in by looking at an example of an object in JavaScript:<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>This is a very simple object with four properties. The first property has the key \u201cname\u201d and the value \u201cDaniel Pataki.\u201d 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\u2019ve 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<p>.gist table { margin-bottom: 0; }<\/p>\n<p>The code above would send a post request to the given URL. The \u201ccomplete\u201d property invokes a function, which is run when the request has been completed. To see how this would work let\u2019s quickly write a function of our own:<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\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\u2019ve 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\u2019s 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\u2019s create a test object with some useful information we can manipulate:<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\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<p>.gist table { margin-bottom: 0; }<\/p>\n<p>And here\u2019s what it looks like in the browser console:<\/p>\n<div class=\"pic-full  \">\n<figure style=\"width: 735px\" class=\"wp-caption aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"attachment-735x735 size-735x735\" src=\"https:\/\/i0.wp.com\/byteplate.com\/wp-content\/uploads\/l-n\/logging-the-object.png?resize=735%2C258\" alt=\"Logging object values\" width=\"735\" height=\"258\" \/><figcaption class=\"wp-caption-text\">Logging object values<\/figcaption><\/figure>\n<\/div>\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<p>.gist table { margin-bottom: 0; }<\/p>\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\u2019s the complete code re-written to use objects:<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>The biggest change you\u2019ll see is that instead an array of tweets and a username given separately, I\u2019ve 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\u2019s properties instead of separate arguments and I\u2019ve removed <code>document.write<\/code> to make sure it just returns a string, which can then be used anywhere.<\/p>\n<\/div>\n<p><!-- end container --><\/p>\n<div class=\"full-blogad full-blogad-courses\" id=\"full-blogad-156655\">\n<div class=\"full-blogad-container\">\n<div class=\"row\">\n<div class=\"col-sm-24 col-md-11 col-md-offset-1\">\n<h3>COURSES<\/h3>\n<h4>WP Academy \u2013 WordPress Wisdom, Bitesized.<\/h4>\n<p>Structured e-learning to expand your WordPress and general business horizons. Learn from people like our very own CEO James Farmer with more than a decade\u2019s experience running a WordPress Business!.<\/p>\n<p>  <a href=\"https:\/\/premium.wpmudev.org\/academy\" class=\"ghost-button-arrow i-wpmudev-tail-arrow open-trial\">LEARN MORE<\/a>\n<\/div>\n<div class=\"col-sm-24 col-md-10 col-md-offset-2\">\n  <img decoding=\"async\" src=\"https:\/\/premium.wpmudev.org\/wp-content\/themes\/wpmudev-2015-1\/assets\/img\/trial\/courses.svg\">\n<\/div>\n<\/div>\n<p><!-- end row --><\/div>\n<p><!-- end full-blogad-container --><\/div>\n<p><!-- end full-blogad --><\/p>\n<div class=\"container\">\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\u2019t 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\u2019re 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<p>.gist table { margin-bottom: 0; }<\/p>\n<p>\u00a0<\/p>\n<p>Let\u2019s 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\u2019s 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\u2019s rewrite our tweet example with constructors in mind:<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>That\u2019s a lot cleaner and a lot more understandable. I\u2019ve 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\u2019ll take a look at jQuery, the JavaScript framework used heavily by WordPress. You\u2019ll learn how to manipulate websites so you can create great things like toggle sections, date drop-downs and more.<\/p>\n<div class='yarpp-related-rss'>\n<p>Related posts:<\/p>\n<ol>\n<li><a href=\"https:\/\/premium.wpmudev.org\/blog\/javascript-for-wordpress-people\/\" rel=\"bookmark\" title=\"JavaScript for WordPress People: What You Need to Know\">JavaScript for WordPress People: What You Need to Know <\/a> <small>At WordCamp US, WordPress co-founder Matt Mullenweg used his State&#8230;<\/small><\/li>\n<li><a href=\"https:\/\/premium.wpmudev.org\/blog\/javascript-wordpress-basics\/\" rel=\"bookmark\" title=\"JavaScript for WordPress Developers: Learning the Basics\">JavaScript for WordPress Developers: Learning the Basics <\/a> <small>JavaScript was developed over 20 years ago at Netscape and&#8230;<\/small><\/li>\n<li><a href=\"https:\/\/premium.wpmudev.org\/blog\/load-posts-ajax\/\" rel=\"bookmark\" title=\"Loading WordPress Posts Dynamically With AJAX\">Loading WordPress Posts Dynamically With AJAX <\/a> <small>AJAX lets you automagically refresh your content without having to&#8230;<\/small><\/li>\n<li><a href=\"https:\/\/premium.wpmudev.org\/blog\/javascript-resources-wordpress\/\" rel=\"bookmark\" title=\"13 Killer JavaScript Resources to Get Up to Speed for WordPress\">13 Killer JavaScript Resources to Get Up to Speed for WordPress <\/a> <small>If you\u2019ve heard that JavaScript is the new PHP (or&#8230;<\/small><\/li>\n<\/ol>\n<\/div>\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. This is the second post &#8230; <\/p>\n<div><a href=\"https:\/\/byteplate.com\/wpmu-dev\/javascript-for-wordpress-developers-getting-started-with-objects\/\" class=\"more-link\">Read More<\/a><\/div>\n","protected":false},"author":1,"featured_media":9232,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[141],"tags":[251,326,124,136],"class_list":["post-9231","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-wpmu-dev","tag-javascript","tag-tutorials","tag-wordpress","tag-wpmu"],"acf":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/byteplate.com\/wp-content\/uploads\/l-n\/logging-the-object.png?fit=1340%2C470&ssl=1","jetpack_shortlink":"https:\/\/wp.me\/p6EepC-2oT","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/posts\/9231","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/comments?post=9231"}],"version-history":[{"count":0,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/posts\/9231\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/media\/9232"}],"wp:attachment":[{"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/media?parent=9231"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/categories?post=9231"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/tags?post=9231"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}