Skip to content

Instantly share code, notes, and snippets.

Created April 27, 2017 13:15
Show Gist options
  • Save anonymous/8461ccdef1cc387d89304f277de108f0 to your computer and use it in GitHub Desktop.
Save anonymous/8461ccdef1cc387d89304f277de108f0 to your computer and use it in GitHub Desktop.
TryCF Gist
<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