JavaScript for the C# Developer Part 6 – Objects

Previous: JavaScript for the C# Developer Part 5 – Closures are Simple

In the posts on functions and closures the demonstrations illustrated procedural and functional programming techniques. JavaScript supports both of these styles, but JavaScript is an object oriented language. In fact unless a variable is undefined, null, boolean, string, or number it is an object. Functions, arrays, dates, and regular expressions are all objects and JavaScript even wraps the primitive types with objects for extensibility.

JavaScript is a classless language that supports inheritance through prototypes. The word prototype is a fancy way of saying ‘model’. Simply put, JavaScript lets you create new objects from existing objects instead of from classes. Prototypes will be covered in a future post. This one focuses on the basics of object creation and manipulation.

Collections of Name-Value Pairs

A JavaScript object is little more than a collection of name-value pairs. The name is a key and can be practically any string of characters. The value can be of any type including function. Values of type function are the only thing that distinguishes a method from a property. Unlike C#, JavaScript lacks property getters and setters. Many libraries, SharePoint’s CSOM included, follow a pattern that uses set_value() and get_value() methods to read and write protected values. However, this style is often a hallmark of a JavaScript library ported from another language, as is the case with CSOM, and is not necessarily a pattern you should follow.

You can access an object’s members by using dot notation (object.member) or square bracket notation (object[‘member’]). Since the size of scripts is generally a concern with web sites, the dot notation is preferred because it uses three less characters and most people find it more readable. One difference is that the bracket notation allows member names that are disallowed with dot notation. Another is that you can access members dynamically with square bracket notation as the following example shows (http://jsfiddle.net/DougWare/W6BcJ/).


In this example the object (remember that functions are objects) has a property named 2 + 2 == 4. Of course this would be a crazy thing to do in real life, but it shows how flexible JavaScript can be. This is in stark contrast to the amount of reflection code required to access a member via reflection in C# and it enables techniques seldom used in C# programs.

Creating Objects with Object Literals

The easiest way to create an object is with a literal expression with JavaScript Object Notation, JSON. In the JSON format the collection of name value pairs is wrapped in curly brackets, names are separated by a colon, and name value pairs are separated by a comma. If a name contains invalid characters, as in the example above, one need simply enclose the name in quotes. Here is an example (http://jsfiddle.net/DougWare/R5ufM/).


 
 

As you can see, JSON is very flexible! Since you can use any valid literal on the left side of the colon you can nest objects and include arrays (http://jsfiddle.net/DougWare/w5Ekn/).


 
 

This flexibility is a key reason so many people use JSON as a data interchange format preferred over XML.

The JSON Object

All of the popular modern browsers include a built-in object named JSON that includes two methods:

  • stringify() – Returns an object as a JSON formatted string
  • parse() – Returns an object from a JSON formatted string

It is worth noting that the JSON object ignores functions (http://jsfiddle.net/DougWare/7YWDg/).


Note that the alert contains an empty object for nestedObject instead of the doMath() function.

Constructor Functions

A function is a type of object. JavaScript includes the keyword new which creates a new empty object instance, executes the function as a constructor, and returns a new object that contains the object as initialized by the constructor. All the constructor must do is use the this keyword to extend the new object instance with the desired properties and methods as follows (http://jsfiddle.net/DougWare/whx3L/).


This example illustrates that the redShirt object and the blueShirt object exist independently of each other and each maintains its own private state.

This is my least favorite way to create objects – I really dislike how the new operator works because it simply changes the behavior of the function call and a call that accidently lacks new looks perfectly fine when you read it! This problem is easily seen in the following example (http://jsfiddle.net/DougWare/3VVzY/).


In this example the assignment to blueShirt is missing the new operator. The constructor function does not return a value and blueShirt is undefined, but the syntax is perfectly valid.

Another problem is that the value of this when new is missing is the window object. As a result, this.color and the other members of the object are attached to window and become global variables! (http://jsfiddle.net/DougWare/pkwrH/).


The behavior of this is one of the most confusing aspects of JavaScript and is the subject of a later post.

The Simple Object Factory Pattern

My personal preference is to use the object factory pattern and avoid the use of new. An object factory is a function that creates, initializes, and returns an object instance based on zero or more input parameters. There are a number of ways you can go about this in JavaScript and my way isn’t necessarily the best. Here are two alternative
approaches the latter of which being a full blown implementation of the pattern. I have no doubt someone will feel compelled to point out that what I’m showing here doesn’t fit the formal definition of the pattern.

My simple factory relies on a closure to give the instances private variables and an object literal to provide the scaffolding of the object. The object literal resembles a class. (http://jsfiddle.net/DougWare/3Z9M6/)


There is Another Way

…but I can’t explain it without first explaining prototypes which will be the topic of the next post, JavaScript for the C# Developer Part 7 – Prototypal Inheritance.

Until then, happy coding,
–Doug

Author: Doug Ware