{"id":303,"date":"2012-05-19T02:50:01","date_gmt":"2012-05-19T02:50:01","guid":{"rendered":"http:\/\/www.thespidercloud.com\/?p=259"},"modified":"2012-05-19T02:50:01","modified_gmt":"2012-05-19T02:50:01","slug":"javascript-object-basics","status":"publish","type":"post","link":"https:\/\/frowningbear.com\/codebase\/2012\/05\/19\/javascript-object-basics\/","title":{"rendered":"Notes on Javascript Objects"},"content":{"rendered":"<style>\ndiv.note, div.note p {background: rgb(255, 243, 212) none repeat scroll 0 0;}<br \/><\/style>\n<p>As the title says, it&#8217;s a bunch of notes and examples on the topic of Objects in Javascript that I have collected over the years. Some are my own and some are unashamedly borrowed from multiple resources on the internet, whose authors are simply too numerous to mention.<\/p>\n<p><!--more--><\/p>\n<h3>Inheritance and the prototype chain<\/h3>\n<p>When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property (referred to as [[Prototype]] ) which holds a\u00a0link to another object called its <strong>prototype<\/strong>. That prototype object has a prototype of its own, and so on until an object is reached with <code>null<\/code> as its prototype. By definition, <code>null<\/code> has no prototype, and acts as the final link in this <strong>prototype chain<\/strong>.<\/p>\n<p>Nearly all objects in JavaScript are instances of <a title=\"The Object constructor creates an object wrapper.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Object\"><code>Object<\/code><\/a> which sits on the top of a prototype chain.<\/p>\n<p>While this is often considered to be one of JavaScript&#8217;s weaknesses, the prototypal inheritance model is in fact more powerful than the classic model.\u00a0It is, for example, fairly trivial to build a classic model on top of a prototypal model.<\/p>\n<h2 id=\"Inheritance_with_the_prototype_chain\" class=\"highlight-spanned\"><span class=\"highlight-span\">Inheritance with the prototype chain<\/span><\/h2>\n<h3 id=\"Inheriting_properties\">Inheriting properties<\/h3>\n<p>JavaScript objects are dynamic &#8220;bags&#8221; of properties (referred to as <strong>own properties<\/strong>). JavaScript objects have a link to a prototype object. When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.<\/p>\n<div class=\"note\">\n<p>Following the ECMAScript standard, the notation <code>someObject.[[Prototype]]<\/code> is used to designate the prototype of <code>someObject.\u00a0<\/code>Since ECMAScript 2015, the <code>[[Prototype]]<\/code> is accessed using the accessors <a title=\"The Object.getPrototypeOf() method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Object\/getPrototypeOf\"><code>Object.getPrototypeOf()<\/code><\/a> and <a title=\"The Object.setPrototypeOf() method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Object\/setPrototypeOf\"><code>Object.setPrototypeOf()<\/code><\/a>. This is equivalent to the JavaScript property <code>__proto__<\/code>\u00a0which is non-standard but\u00a0de-facto implemented by many browsers.<\/p>\n<p>It should not be confused with the <code><em>func<\/em>.prototype<\/code>\u00a0property of functions, which instead specifies the\u00a0<code>[[Prototype]]<\/code>\u00a0to be assigned\u00a0to\u00a0all\u00a0<em>instances<\/em>\u00a0of objects created by the given function when used as a constructor. The <code><strong>Object.prototype<\/strong><\/code> property represents the <a title=\"The Object constructor creates an object wrapper.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Object\"><code>Object<\/code><\/a> prototype object.<\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The <code><strong>Object.setPrototypeOf()<\/strong><\/code> method sets the prototype (i.e., the internal <code>[[Prototype]]<\/code> property) of a specified object to another object or <a title=\"The value null\u00a0represents the intentional absence of any object value. It is one of JavaScript's primitive values.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/null\"><code>null<\/code><\/a>.<\/p>\n<div class=\"warning\">\n<p><strong>Warning:<\/strong> Changing the <code>[[Prototype]]<\/code> of an object is, by the nature of how modern JavaScript engines optimize property accesses, a very slow operation, in <strong><em>every<\/em><\/strong> browser and JavaScript engine. The effects on performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in <code>obj.__proto__ = ...<\/code> statement, but may extend to <strong><em>any<\/em><\/strong> code that has access to <strong><em>any<\/em><\/strong> object whose <code>[[Prototype]]<\/code> has been altered. If you care about performance you should avoid setting the <code>[[Prototype]]<\/code> of an object. Instead, create a new object with the desired <code>[[Prototype]]<\/code> using <a title=\"The Object.create() method creates a new object with the specified prototype object and properties.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Object\/create\"><code>Object.create()<\/code><\/a>.<\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<p><code>Object.setPrototypeOf()<\/code> is in the ECMAScript 2015 specification. It is generally considered the proper way to set the prototype of an object, vs. the more controversial\u00a0<a title=\"The __proto__ property of Object.prototype is an accessor property (a getter function and a setter function) that exposes the internal [[Prototype]] (either an object or null) of the object through which it is accessed.\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Object\/__proto__\"><code>Object.prototype.__proto__<\/code><\/a> property.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>JavaScript has a special keyword, this, that you can use within a method to refer to the current object.<\/p>\n<p>Javascript supports OOP because it supports inheritance through prototyping as well as properties and methods.<\/p>\n<p>Note that an object is just a special kind of data.<\/p>\n<p>Objects contain one or more key-value pairs. The key portion can be any string. The value portion can be any type of value: a number, a string, an array, a function, or even another object.<\/p>\n<p>[Definition: When one of these values is a function, it\u2019s called a method of the object.] Otherwise, they are called properties.<\/p>\n<p>As it turns out, nearly everything in JavaScript is an object \u2014 arrays, functions, numbers, even strings \u2014 and they all have properties and methods.<\/p>\n<p>An object has properties and methods.<\/p>\n<p>Note that methods are just functions attached to objects<\/p>\n<p>Properties are variables created inside an object and methods are functions created inside an object.<\/p>\n<p>In JavaScript you can define your own objects.<\/p>\n<p>In addition, you can assign methods and properties to each object, pre-written or self-defined.<\/p>\n<p>* Methods are &#8216;things that do something&#8217;, they can be recognized by their brackets (). When you call them, like object.method(), something happens.<\/p>\n<p>* Properties are &#8216;things that are something&#8217;. They have a value, for instance a number, a string or a Boolean value. When you call them, like object.property, you get (or set) this value.<\/p>\n<p>Normal JavaScript functions are also methods (hence the brackets).<\/p>\n<p>document.write(&#8216;text&#8217;) executes the pre-defined write() method of the document object.<br \/>\nIf you write your own functions you add methods to the window object, the parent of all other JavaScript objects.<\/p>\n<p>While using the new operator or literal notion to create a custom object is both simple and logical, the biggest shortcoming is that the result is NOT reusable- we cannot easily initialize different versions of the created object. For example with the first demonstration above, if the person&#8217;s name is not &#8220;Tim Scarfe&#8221;, we would need to redefine our entire object just to accommodate this change.<\/p>\n<p>Whereas an array holds a list in a certain order, an object is an unordered collection.<br \/>\nObjects hold attributes that point to values.<br \/>\nA value could be one number or a single line of text.<br \/>\nOr, a value can be an array<\/p>\n<p>Creating objects using new Object()<\/p>\n<p>There are several ways to create objects in JavaScript, and all of them have their place. The simplest way is to use the new operator, specifically, new Object():<\/p>\n<p>Below we define a custom object &#8220;person,&#8221; then add to it its own properties and method afterwards. In this case, the custom method merely initializes two more properties.<\/p>\n<p>person = new Object()<br \/>\nperson.name = &#8220;Tim Scarfe&#8221;<br \/>\nperson.height = &#8220;6Ft&#8221;<\/p>\n<p>person.run = function() {<br \/>\nthis.state = &#8220;running&#8221;<br \/>\nthis.speed = &#8220;4ms^-1&#8221;<br \/>\n}<\/p>\n<p>OBJECT LITERAL<\/p>\n<p>What is an object literal? In nontechnical terms, it is a means of containing a lot of data in one tidy package.<br \/>\nIt is a comma separated list of name value pairs wrapped in curly braces.<br \/>\nObject literals are used as a means of encapsulating data, avoiding the use of global variables which can cause problems when combining code.<\/p>\n<p>How and Why We Use Object Literals<\/p>\n<p>Objects literals enable us to write code that supports lots of features yet still make it a relatively straightforward for the implementers of our code. No need to invoke constructors directly or maintain the correct order of arguments passed to functions, etc.<\/p>\n<p>Object literals are also useful for unobtrusive event handling, as a way of holding data that would otherwise have been passed to functions called from HTML event handler attributes.<\/p>\n<p>TIP. The literal notation of creating JavaScript objects has one weakness \u2013 it can only be used to describe objects. With other words, using the literal notation you can only define (key, value) pairs, but you can\u2019t create classes, class constructors, or other reusable components of code.<\/p>\n<p>Creating objects using Literal Notation<\/p>\n<p>Another inline way of defining an object is via literal notation. Supported in JavaScript1.2 and above, it&#8217;s a more robust form of creating an object on the fly:<\/p>\n<p>Literal notion can contain arrays or arbitrary JavaScript expressions or values.<\/p>\n<p>Dot notation is faster to write and clearer to read.<\/p>\n<p>Square bracket notation allows access to properties containing special characters and selection of properties using variables.<\/p>\n<p>In JavaScript an object literal is declared or defined as follows:<\/p>\n<p>var myObject = {}<\/p>\n<p>An object literal with a few properties, from a Rotating Images example:<\/p>\n<p>var myRotator = {<br \/>\npath: &#8216;images\/&#8217;,<br \/>\nspeed: 4500,<br \/>\nimages: [&#8220;smile.gif&#8221;, &#8220;grim.gif&#8221;, &#8220;frown.gif&#8221;, &#8220;bomb.gif&#8221;]<br \/>\n}<\/p>\n<p>\/\/ Object Literals<\/p>\n<p>timObject = {<br \/>\nproperty1 : &#8220;Hello&#8221;,<br \/>\nproperty2 : &#8220;MmmMMm&#8221;,<br \/>\nproperty3 : [&#8220;mmm&#8221;, 2, 3, 6, &#8220;kkk&#8221;],<br \/>\nmethod1 : function(){alert(&#8220;Method had been called&#8221; + this.property1)}<br \/>\n};<\/p>\n<p>timObject.method1();<br \/>\nalert(timObject.property3[2]) \/\/ will yield 3<\/p>\n<p>Creating Objects<\/p>\n<p>To demonstrate, let\u2019s create a new object that has three properties; two store numeric values, while the other is an anonymous function (a function with no name):<\/p>\n<p>var AnimationManager = {<br \/>\nframesPerSecond: 30,<br \/>\ntotalLength: 15,<br \/>\nstartAnimation: function(){ \/* code goes here *\/ }<br \/>\n}<\/p>\n<p>It\u2019s important to note that the object literal is really just a shortcut to creating objects using JavaScript\u2019s built-in Object type. We\u2019ll explore the code in more detail later, but for now just remember that we could also create the AnimationManager object with the following:<\/p>\n<p>var AnimationManager = new Object();<br \/>\nAnimationManager.framesPerSecond = 30;<br \/>\nAnimationManager.totalLength = 15;<br \/>\nAnimationManager.startAnimation = function () { \/* code goes here *\/ };<\/p>\n<p>JSON uses object literal notation. The form:<\/p>\n<p>var person = {<br \/>\n&#8220;name&#8221;: &#8220;Douglas Adams&#8221;<br \/>\n&#8220;age&#8221;: 42<br \/>\n};<\/p>\n<p>Is exactly the same (for all intents and purposes) as:<\/p>\n<p>var person = new Object();<br \/>\nperson.name = &#8220;Douglas Adams&#8221;;<br \/>\nperson.age = 42;<\/p>\n<p>Does that help you?<\/p>\n<p>You can also use<\/p>\n<p>person[&#8220;age&#8221;]<\/p>\n<p>this is the same as<\/p>\n<p>person.age<\/p>\n<p>and to iterate through named properties:<\/p>\n<p>\/\/prints the person.propertyName for all propertyName in person<br \/>\nfor (var propertyName in person) {<br \/>\nalert(person[propertyName]);<br \/>\n}<\/p>\n<p>var o = {a:1, b:2, c:3};<\/p>\n<p>function show_props(obj, objName) {<br \/>\nvar result = &#8220;&#8221;;<br \/>\nfor (var i in obj) {<br \/>\nresult += objName + &#8220;.&#8221; + i + &#8221; = &#8221; + obj[i] + &#8220;\\n&#8221;;<br \/>\n}<br \/>\nreturn result;<br \/>\n}<\/p>\n<p>alert(show_props(o, &#8220;o&#8221;));<br \/>\n\/* alerts :<br \/>\no.a = 1<br \/>\no.b = 2<br \/>\no.c = 3<br \/>\n16.*\/<\/p>\n<p>Hash Tables &#8211; all 4 examples below are equivalent<\/p>\n<p>var myHashtable = {}; \/\/ object literal ?<br \/>\nmyHashtable[&#8220;name&#8221;] = &#8220;Carl&#8221;;<br \/>\nmyHashtable.city = &#8220;Anytown&#8221;;<\/p>\n<p>var myHashtable = {name : &#8220;Carl&#8221;, city : &#8220;Anytown&#8221;}; \/\/ object literal<\/p>\n<p>var myHashtable = {&#8220;name&#8221; : &#8220;Carl&#8221;, &#8220;city&#8221; : &#8220;Anytown&#8221;}; \/\/ json<\/p>\n<p>var myHashtable = new Object(); \/\/ object<br \/>\nmyHashtable[&#8220;name&#8221;] = &#8220;Carl&#8221;;<br \/>\nmyHashtable.city = &#8220;Anytown&#8221;;<\/p>\n<p>Object Constructor<br \/>\nWe need a way to create an object &#8220;type&#8221; that can be used multiple times without having to redefine the object every time to meet each particular instance&#8217;s needs. The standard way to achieve this is to use the Object Constructor function.<\/p>\n<p>An object constructor is merely a regular JavaScript function, so it&#8217;s just as robust (ie: define parameters, call other functions etc). The difference between the two is that a constructor function is called via the new operator (which you&#8217;ll see below). By basing our object definition on the function syntax, we get its robustness as well.<\/p>\n<p>function cat(name) {<br \/>\n05 this.name = name;<br \/>\n06 this.talk = function() {<br \/>\n07 alert( this.name + &#8221; say meeow!&#8221; )<br \/>\n08 }<br \/>\n09 }<br \/>\n10<br \/>\n11 cat1 = new cat(&#8220;felix&#8221;)<br \/>\n12 cat1.talk() \/\/alerts &#8220;felix says meeow!&#8221;<br \/>\n13<br \/>\n14 cat2 = new cat(&#8220;ginger&#8221;)<br \/>\n15 cat2.talk() \/\/alerts &#8220;ginger says meeow!&#8221;<\/p>\n<p>Here the function &#8220;cat()&#8221; is an object constructor, and its properties and methods are declared inside it by prefixing them with the keyword &#8220;this.&#8221; Objects defined using an object constructor are then instantiated using the new keyword. Notice how we&#8217;re able to easily define multiple instances of cat, each with its own name- that&#8217;s the flexibility object constructor brings to custom objects. Constructors create the blueprints for objects, not the object itself.<\/p>\n<p>Adding methods to our object using prototype<\/p>\n<p>We saw above how to add a method to our constructor function by merely declaring it inside the function. Another approach is through prototyping, which is also more popular due to its elegance. Prototype is a type of inheritance in JavaScript. We use it when we would like an object to inherit a method after it has been defined. Think of prototyping mentally as &#8220;attaching&#8221; a method to an object after it&#8217;s been defined, in which all object instances then instantly share.<\/p>\n<p>Lets extend our original cat() object above with an additional method to change the cat&#8217;s name, using prototype:<\/p>\n<p>cat.prototype.changeName = function(name) {<br \/>\nthis.name = name;<br \/>\n}<\/p>\n<p>firstCat = new cat(&#8220;pursur&#8221;)<br \/>\nfirstCat.changeName(&#8220;Bill&#8221;)<br \/>\nfirstCat.talk() \/\/alerts &#8220;Bill says meeow!&#8221;<\/p>\n<p>As you can see we merely use the keyword &#8220;prototype&#8221; immediately following the object&#8217;s name to utilize this functionality. The custom method changeName() is now shared by all instances of cat.<\/p>\n<p>Prototyping works on both custom objects and select prebuilt objects, such as Date() or String. For the later, the general rule is that you can prototype any prebuilt object that&#8217;s initialized with the &#8220;new&#8221; keyword.<\/p>\n<p>As we have seen, JavaScript supports prototype inheritance instead of class based. It&#8217;s possible for inheritance to happen other ways, however.<\/p>\n<p>The following is an example of inheritance through functions.<\/p>\n<p>function superClass() {<br \/>\nthis.supertest = superTest; \/\/attach method superTest<br \/>\n}<\/p>\n<p>function subClass() {<br \/>\nthis.inheritFrom = superClass;<br \/>\nthis.inheritFrom();<br \/>\nthis.subtest = subTest; \/\/attach method subTest<br \/>\n}<\/p>\n<p>function superTest() {<br \/>\nreturn &#8220;superTest&#8221;;<br \/>\n}<\/p>\n<p>function subTest() {<br \/>\nreturn &#8220;subTest&#8221;;<br \/>\n}<\/p>\n<p>var newClass = new subClass();<\/p>\n<p>alert(newClass.subtest()); \/\/ yields &#8220;subTest&#8221;<br \/>\nalert(newClass.supertest()); \/\/ yields &#8220;superTest&#8221;<\/p>\n<p>Prototype based inheritance is a far better bet for JavaScript applications in most cases.<\/p>\n<p>The prototype object of JavaScript, introduced starting in JavaScript 1.1, is a prebuilt object that simplifies the process of adding custom properties\/ methods to all instances of an object.<\/p>\n<p>The prototype object is here to help when you wish to quickly add a custom property to an object that is reflected on all instances of it. To use this object, simply reference the keyword &#8220;prototype&#8221; on the object before adding the custom property to it, and this property is instantly attached to all instances of the object<\/p>\n<p>There is an important thing to take note at this point in the tutorial. While you are free to use the prototype object on any custom objects, this is NOT the case with prebuilt ones (such as image, string etc). JavaScript only allows you to &#8220;prototype&#8221; prebuilt objects that are created with the new keyword, such as the following:<\/p>\n<p>* The image object<br \/>\n* The string object<br \/>\n* The date object<br \/>\n* The Array object<\/p>\n<p>Once we&#8217;ve defined an object function, we have to instantiate it to actually use it. Instantiating an object function means using the keyword &#8220;new&#8221; in front of the object name, and then creating an instance of the object by assigning it to a variable:<\/p>\n<p>Function objects can be a little more useful than the object literals we just discussed, though, in that they can be used as a template for new objects.<\/p>\n<p>For those unfamiliar with object-oriented programming, this object template is also known as a class. Instead of starting with a blank slate each time, objects built from a class are pre-populated with methods and properties. By defining a new function object, we are, in effect, defining a blueprint for new objects that we can use over and over again.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>As the title says, it&#8217;s a bunch of notes and examples on the topic of Objects in Javascript that I have collected over the years. Some are my own and some are unashamedly borrowed from multiple resources on the internet, whose authors are simply too numerous to mention.<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[3],"tags":[],"class_list":["post-303","post","type-post","status-publish","format-standard","hentry","category-javascript"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/303","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/comments?post=303"}],"version-history":[{"count":0,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/303\/revisions"}],"wp:attachment":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/media?parent=303"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/categories?post=303"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/tags?post=303"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}