JavaScript: Object Literal Scope Clarification

I am using JavaScript in a project I am working on, and encountered a problem for which I could not recall the answer.  I am creating a rough JavaScript equivalent of a singleton object using object literal notation.  Some of the properties of this singleton object are functions, that need to access other properties of the same object.  A simple example of what I want to do is this:

What I wasn’t sure of is the simplest, clearest way to accomplish the summation of the a and b properties in the aplusb function. In the past, I had simply used MySingleton.a and MySingleton.b.  Giving this:

This works, but becomes messy very quickly when dealing with multiple layers of objects and functions.  Having to start at the outermost object and “dot” your way down the objects is sloppy.  The solution would be the “this” keyword provided it pointed at the current object, not the function or anything else weird.  I wasn’t entirely clear on whether you could use the “this” keyword to accomplish what I was aiming for, so I tested it with code like the following.

And low and behold, it works.  “this” will clean up my code, and make it less tedious to write and read.  A working jsFiddle of this code can be found at http://jsfiddle.net/jtmorris/mDy26/  If you have an object literal, and want to refer to other properties from a function property, “this” is the key.

Leave a Reply