I grabbed the speaker’s deck and used it as a guideline, but I spent the majority of the time in jsfiddle.net writing examples. The audience was really interactive and grasped the basics pretty quickly. The topics that we spent the most amount of time discussing as a group where regarding namespaces, functions and objects. So I thought I might include 3 of the examples here on my blog.
Creating an Object Literal
Objects can be created in a variety of ways. But the most common you will see in demos is the object literal. The reason? Its short and sweet. Objects can be created simply by setting a variable equal to an open and close curly brace pair, as shown below. Then add properties as needed. I often use this syntax for simple objects (not a lot of logic, mostly properties and a few methods).
The ‘this’ keyword does work with the object literal, though once you get into nesting functions it can get unwieldy unless you manage ‘this’. That’s often when I use one of a few techniques such as setting ‘this’ (at a place where you know what ‘this’ represents for certain) to a variable called self. But I’ll hit that topic in a later post.
I most often use object literals for passing arguments to functions
Creating an Object from a Function
You can also create objects through functions. While I prefer using a pattern such as the Revealing Module pattern for this, the simplest way to create an object from a function is shown below. Note that use of ‘self’ in here to represent ‘this’. It may not be needed in all cases but it’s a good habit to get into that has saved me many times. A friend of mine actually uses the word ’me’ instead of self … says its twice as fast