Geeks With Blogs
Phubar Baz Musings of an HTML5 Programmer

Here's a pattern I use a lot to encapsulate properties in JavaScript objects. I call it the Chainable Property Pattern because it is used to define get/set operations for properties that can be chained together into one statement.

We start with an object with a private variable.

function MyObject()
{
var count = 0;

Next we create a public property accessor method.

this.count = function(newCount)
{
if (arguments.length)
{
count = newCount;
return this;
}
return count;
}
}

Let's take a look at how this works. First we use arguments.length to determine if a parameter was passed to the method. If so the user is setting the value of the property. So we set the private variable to the new value and return "this". Returning "this" is what allows us to chain calls together. If no variables were passed in the user wants to get the value of the property so we simply return its value.

Now we can set and get the property like this:

var obj = new MyObject();
obj.count(3); // set count to 3
console.log(obj.count()); // get count

Now let's say we have an object with many different properties. We can set them all in one chained call.

var obj = new MyObject().count(3).someOtherProperty(5);

Since every set property call returns a pointer to the object we can call the methods one after the other. We can even call them off the constructor and still get the new object's reference.

Posted on Thursday, June 13, 2013 10:47 AM | Back to top


Comments on this post: Chainable Property Pattern

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © PhubarBaz | Powered by: GeeksWithBlogs.net