Created
April 27, 2017 14:11
-
-
Save anonymous/a5c8771bac3d0821bab0a2fb17b45e1e to your computer and use it in GitHub Desktop.
TryCF Gist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> | |
//this version encapsulates the value, you cannot update it from the outside | |
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(var=make(1).add(2), expand=false); | |
//this version exposes the value, and allows you to see and update it outside | |
function makeExposedProperties (required numeric input) { | |
var o = { | |
add: function (required numeric input) { | |
o.value += input; | |
return o; | |
}, | |
subtract: function (required numeric input) { | |
o.value -= input; | |
return o; | |
}, | |
multiply: function (required numeric input) { | |
o.value *= input; | |
return o; | |
}, | |
divide: function (required numeric input) { | |
o.value /= input; | |
return o; | |
}, | |
get: function () { | |
return o.value; | |
}, | |
value: input | |
}; | |
return o; | |
} | |
print(makeExposedProperties(1).value, "makeExposedProperties(1).value"); | |
print(makeExposedProperties(1).add(1).value, "makeExposedProperties(1).add(1).value"); | |
print(makeExposedProperties(2).add(3).subtract(1).multiply(5).divide(6).value, "makeExposedProperties(2).add(3).subtract(1).multiply(5).divide(6).value"); | |
x = makeExposedProperties(1).add(1); | |
x.value += 1; | |
print(x.add(1).get(), "x = makeExposedProperties(1).add(1);x.value += 1;x.add(1).get()"); | |
writedump(var=makeExposedProperties(1).add(2), expand=false); | |
</cfscript> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment