Friday, September 5, 2014

Using closures to make structs behave like objects

When they added closures and anonymous functions to Coldfusion in version 10 it opened up a lot of interesting new avenues to explore.  Some of these are very useful.  Anonymous functions can be created and passed as arguments to other functions without having to separately create a named function.  They added callback arguments to some of the array functions and various others.

Closures allow us to access variables that exist when the function is created, in the same way we do in javascript.  With that ability we can do some very interesting things with structs.



The example above shows how we can create a struct with a function that updates one of the other keys in the struct.  This is very much like an object with properties and methods.  Inside a function we create a var'ed struct named this.  I used the name "this" for the struct, but that name has no special significance here.  I added the value property and a method to set the value.  When we run that code we get the following output.


You can see the struct with the initial value of 5.  Then after the call to setValue it has changed to 10.  Then I dumped out the variables scope just to show that nothing odd is being set outside the struct.

This is interesting but I think we can go further with this idea.  What if we want our object to have private properties.



The code in this example var's the value property instead of adding it to the this struct.  Then I have added a getValue method.  This code produces the following output.



So you can see the value property is not exposed in the dumps of the struct, but we are able to access it and change it with the getValue and setValue methods.

Now we have demonstrated private and public properties, and we have public methods.  I think you can imagine how to create a private method by var'ing a variable and setting it equal to a function.  I wont demonstrate that.

That's all I have for now.  In a future article I may explore inheritance and some other object oriented topics.


No comments:

Post a Comment

Coding

  I'm not sure where I heard this, and it wasn't worded this way, but it helps to think about coding this way. Basically, any progra...