I’m not sure how I missed this before but among the long list of things added to ColdFusion 9 is the ability to create a CFC using the “New” syntax. Up until now, to create a new object from a CFC we’d use the createObject()
method like so
<cfset Team = createObject("component", "model.Team") /></pre>Now, using the New keyword, we can shorten that to <pre lang="cfm"><cfset Team = New model.Team() />
But wait, there’s more!
When you use the New keyword, ColdFusion will automatically look for and run any init()
method that exists in the CFC. It also respects any arguments that your init()
method specifies, meaning that if you have a Team.init()
method that can accept team name, color and manager arguments, you can build them right into your the same line of code used to create your object like so
<cfset Team = New model.Team( "Bumblebees", "Yellow", "Benny Bee" ) />
Likewise, as you’d expect, named arguments are still supported. So if you had to send in arguments out of order or needed to omit some optional arguments at object creation, you could do
<cfset Team = New model.Team( manager="Benny Bee", color="Yellow", name="Bumblebees") />
I personally am going to make a point to start using this in my code because I can never seem to spell the word “component” correctly in the createObject()
method.