Skip to content

Instantly share code, notes, and snippets.

@cfvonner
Forked from anonymous/trycf-gist.cfm
Last active April 27, 2017 16:19
Show Gist options
  • Save cfvonner/cb98cd070a53a40966e27a5fdc9f9d32 to your computer and use it in GitHub Desktop.
Save cfvonner/cb98cd070a53a40966e27a5fdc9f9d32 to your computer and use it in GitHub Desktop.
Using Closures to create an "object-like" struct
<p>Using closures, it is possible to create an "object-like" struct with cfml and not using any components. It allows you to do encapsulation, have methods, do chaining, etc. It's api is pretty much identical to an object, except that you use a function to create it (instead of new). ACF10+ and Lucee 4.5+</p>
<cfscript>
function make (required numeric input) {
var value = input;
var o = {
add: function (required numeric input) {
value += input;
return o;
},
subtract: function (required numeric input) {
value -= input;
return o;
},
multiply: function (required numeric input) {
value *= input;
return o;
},
divide: function (required numeric input) {
value /= input;
return o;
},
get: function () {
return value;
}
};
return o;
}
function print (value, label) {
writeoutput("<pre>" & label & ": " & value & "<br /></pre>");
}
print(make(1).get(), "make(1).get()");
print(make(1).add(1).get(), "make(1).add(1).get()");
print(make(2).add(3).subtract(1).multiply(5).divide(6).get(), "make(2).add(3).subtract(1).multiply(5).divide(6).get()");
writedump(make(1));
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment