{"id":1605,"date":"2018-11-06T14:21:17","date_gmt":"2018-11-06T14:21:17","guid":{"rendered":"https:\/\/www.courses.tegabrain.com\/cc18\/?page_id=1605"},"modified":"2018-11-06T14:32:40","modified_gmt":"2018-11-06T14:32:40","slug":"javascript-object-literals","status":"publish","type":"page","link":"https:\/\/www.courses.tegabrain.com\/cc18\/javascript-object-literals\/","title":{"rendered":"Javascript Object Literals"},"content":{"rendered":"<p><script src=\"\/\/toolness.github.io\/p5.js-widget\/p5-widget.js\"><\/script><br \/>\nThis tutorial covers the following:<\/p>\n<ol>\n<li>Review of Arrays<\/li>\n<li>2D Arrays<\/li>\n<li>Objects literals<\/li>\n<li>Objects literals with methods<\/li>\n<\/ol>\n<p>These examples are taken from <a href=\"http:\/\/www.decontextualize.com\/\">Allison Parrish.<\/a><\/p>\n<h2>1. A Review of Arrays.<\/h2>\n<h2 id=\"adding-items-to-an-array\">Adding items to an array<\/h2>\n<p>Remember arrays in javascript (unlike in Processing) can change length. Therefore we can add to them when our code is running.<\/p>\n<p><code>push()<\/code> adds an item to the array. In the following example, we use this method to add a falling rectangle to the sketch whenever the user clicks:<\/p>\n<pre><script type=\"text\/p5\">\r\nvar rectY = []; \/\/ start with empty list\r\nfunction setup() {\r\n  createCanvas(400, 400);\r\n}\r\nfunction draw() {\r\n  background(50);\r\n  noStroke();\r\n  rectMode(CENTER);\r\n  fill(255);\r\n  for (var i = 0; i < rectY.length; i++) {\r\n    rect(200, rectY[i], 50, 25);\r\n    rectY[i] += 1;\r\n  }\r\n}\r\nfunction mousePressed() {\r\n  rectY.push(0);\r\n}\r\n<\/script>\r\n<\/pre>\n<p>&nbsp;<\/p>\n<h2 id=\"keeping-track-of-multiple-properties\">3. 2D Arrays, Keeping track of multiple properties<\/h2>\n<p>But how would you make a sketch so that when you click the screen, a rectangle appears <em>at the coordinates of the mouse click<\/em> and then moves downward from there.<\/p>\n<p>For this, we\u2019ll need to keep track of <em>two<\/em> values for each rectangle. This is a bit tricky, and there\u2019s more than one way to do it, each with their own benefits and drawbacks. We\u2019re going to implement two options.<\/p>\n<h2 id=\"arrays-inside-arrays\">Arrays inside arrays<\/h2>\n<p>One solution relies on the fact that <em>arrays themselves are values<\/em>, and so we can store an array <em>inside<\/em> another array. To demonstrate, type the following into an empty sketch and example the debug output:<\/p>\n<pre><code>var stuff = [];\r\nstuff.push([24, 25]);\r\nstuff.push([26, 27]);\r\nconsole.log(stuff); \/\/ displays [[24,25],[26,27]]\r\n<\/code><\/pre>\n<p>After you run this code, the variable <code>stuff<\/code> is an array which has two elements, both of which are <em>themselves<\/em> arrays. If you get the value at index zero, you get an array:<\/p>\n<pre><code>console.log(stuff[0]); \/\/ displays [24,25]\r\n<\/code><\/pre>\n<p>To get one of the two values from <em>that<\/em> array, you need to take the expression that evaluates to the outer array and use the square bracket syntax on that expression to get the inner value out, like so:<\/p>\n<pre><code>console.log(stuff[0][1]); \/\/ displays 25\r\n<\/code><\/pre>\n<p>We can use this idiom to create a version of our falling rectangle sketch that has just <em>one <\/em>array to store information about all rectangles. Each element of that array is itself an array.<\/p>\n<pre><script type=\"text\/p5\">\r\nvar rectXY = []; \/\/ start with empty list\r\nfunction setup() {\r\n  createCanvas(400, 400);\r\n}\r\nfunction draw() {\r\n  background(50);\r\n  noStroke();\r\n  rectMode(CENTER);\r\n  fill(255);\r\n  for (var i = 0; i < rectXY.length; i++) {\r\n    rect(rectXY[i][0], rectXY[i][1], 50, 25);\r\n    rectXY[i][1] += 1;\r\n  }\r\n}\r\nfunction mousePressed() {\r\n  rectXY.push([mouseX, mouseY]);\r\n}\r\n<\/script>\r\n<\/pre>\n<p>The beauty of this is that we can easily add a third attribute to each rectangle simply by adding a third element to the array that we add to the rectXY array on each click. In the following example, a random value is stored in index 2 on each click, and then this number is used to give each rectangle a random color in draw():<\/p>\n<pre><script type=\"text\/p5\">\r\nvar rectXY = []; \/\/ start with empty list\r\nfunction setup() {\r\n  createCanvas(400, 400);\r\n}\r\nfunction draw() {\r\n  background(50);\r\n  noStroke();\r\n  rectMode(CENTER);\r\n  fill(255);\r\n  for (var i = 0; i < rectXY.length; i++) {\r\n    fill(rectXY[i][2]);\r\n    rect(rectXY[i][0], rectXY[i][1], 50, 25);\r\n    rectXY[i][1] += 1;\r\n  }\r\n}\r\nfunction mousePressed() {\r\n  rectXY.push([mouseX, mouseY, random(255)]);\r\n}\r\n<\/script>\r\n<\/pre>\n<p>EXERCISE: Try adding a fourth element to the array that controls how fast the rectangle falls.<\/p>\n<h3 id=\"rectangles-as-objects\">3. Object Literals: Rectangles as Objects<\/h3>\n<p>Here\u2019s a version of our rectangle sketch that puts it all together. On each click, this sketch creates a new object and pushes it into the <code>rectObjs<\/code> array. This is another syntax for a Javascript object called an object literal.<\/p>\n<p>In <code>draw()<\/code>, each rectangle is displayed by accessing the values using the appropriate keys:<\/p>\n<pre><script type=\"text\/p5\">\r\nvar rectObjs = []; \/\/ start with empty list\r\nfunction setup() {\r\n  createCanvas(400, 400);\r\n}\r\nfunction draw() {\r\n  background(50);\r\n  noStroke();\r\n  rectMode(CENTER);\r\n  fill(255);\r\n  for (var i = 0; i < rectObjs.length; i++) {\r\n    fill(rectObjs[i].fillColor);\r\n    rect(rectObjs[i].xpos,\r\n        rectObjs[i].ypos, 50, 25);\r\n    rectObjs[i].ypos += 1;\r\n  }\r\n}\r\nfunction mousePressed() {\r\n  rectObjs.push(\r\n   {\r\n     xpos: mouseX, \r\n     ypos: mouseY,\r\n     fillColor: random(255)\r\n    }\r\n  )\r\n}\r\n<\/script>\r\n<\/pre>\n<p>EXERCISE: Modify the above example so that each rectangle object also stores a separate speed for the X and Y coordinates, then modify the draw() loop so that the rectangles move in directions other than downwards.<\/p>\n<h3>Objects Literals with Methods<\/h3>\n<p>A method is just a function that is the value for a key in an object. For example, try running this code in an empty p5.js sketch:<\/p>\n<pre lang=\"java\">var rectangle = {\r\n    width: 100,\r\n    height: 200,\r\n    area: function() {\r\n        return this.width * this.height;\r\n    },\r\n    perimeter: function() {\r\n        return 2*this.width + 2*this.height;\r\n    }\r\n};\r\nconsole.log(rectangle.area()); \/\/ 20000\r\nconsole.log(rectangle.perimeter()); \/\/ 600\r\n<\/pre>\n<p>This code creates an object named <code>rectangle<\/code>, which has four attributes: the values for <code>width<\/code> and <code>height<\/code> are both numbers, and the values for <code>area<\/code> and <code>perimeter<\/code> are both <em>function values<\/em>. Because these functions are values in an object, we call them methods.<\/p>\n<p>There are two bits of syntax you need to know to get started using methods. The first is how to <em>call<\/em> a method. To do this, take an expression that evaluates to an object, follow it by a dot (<code>.<\/code>), and then type the name of the method, followed by parentheses. (Methods can also take parameters, in which case the parentheses won\u2019t be empty. See below.)<\/p>\n<p>The second bit of new syntax is <code>this<\/code>. <em>Inside<\/em> of the method, there\u2019s a special keyword <code>this<\/code> which refers to <em>the object that contains the method<\/em>. You can access properties, overwrite properties, add new properties, and even call methods of the containing object.<\/p>\n<p>Here\u2019s a version of the example from above. This time, however, the <code>mousePressed()<\/code>function adds objects to the array that have methods of their own for <code>display()<\/code> and <code>update()<\/code>.<\/p>\n<pre><script type=\"text\/p5\">\r\nvar rectObjs = []; \/\/ start with empty list\r\nfunction setup() {\r\n  createCanvas(400, 400);\r\n}\r\nfunction draw() {\r\n  background(50);\r\n  noStroke();\r\n  rectMode(CENTER);\r\n  fill(255);\r\n  for (var i = 0; i < rectObjs.length; i++) {\r\n    rectObjs[i].display();\r\n    rectObjs[i].update();\r\n  }\r\n}\r\nfunction mousePressed() {\r\n  var newRect = {\r\n    xpos: mouseX,\r\n    ypos: mouseY,\r\n    fillColor: random(255),\r\n    display: function() {\r\n      fill(this.fillColor);\r\n      rect(this.xpos, this.ypos, 50, 25);\r\n    },\r\n    update: function() {\r\n      this.ypos += 1;\r\n    }\r\n  };\r\n  rectObjs.push(newRect);\r\n}\r\n<\/script>\r\n<\/pre>\n<p>EXERCISE: Modify the above example so that each rectangle object includes speed variables in the X and Y directions. Modify the methods to also include this.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This tutorial covers the following: Review of Arrays 2D Arrays Objects literals Objects literals with methods These examples are taken from Allison Parrish. 1. A Review of Arrays. Adding items to an array Remember arrays in javascript (unlike in Processing) can change length. Therefore we can add to them when our code is running. push()<a class=\"more-link button\" href=\"https:\/\/www.courses.tegabrain.com\/cc18\/javascript-object-literals\/\">Read More<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"jetpack_post_was_ever_published":false,"footnotes":""},"class_list":["post-1605","page","type-page","status-publish","hentry"],"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/Paeb9f-pT","jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/www.courses.tegabrain.com\/cc18\/wp-json\/wp\/v2\/pages\/1605","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.courses.tegabrain.com\/cc18\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.courses.tegabrain.com\/cc18\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.courses.tegabrain.com\/cc18\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.courses.tegabrain.com\/cc18\/wp-json\/wp\/v2\/comments?post=1605"}],"version-history":[{"count":3,"href":"https:\/\/www.courses.tegabrain.com\/cc18\/wp-json\/wp\/v2\/pages\/1605\/revisions"}],"predecessor-version":[{"id":1614,"href":"https:\/\/www.courses.tegabrain.com\/cc18\/wp-json\/wp\/v2\/pages\/1605\/revisions\/1614"}],"wp:attachment":[{"href":"https:\/\/www.courses.tegabrain.com\/cc18\/wp-json\/wp\/v2\/media?parent=1605"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}