对ColdFusion中的类,实例和方法感到困惑

时间:2011-04-19 19:26:25

标签: oop coldfusion

我的问题可能最好用一个例子说明。在javascript中,我习惯于能够做到这样的事情:

// create a simple class
function myClass() {
  this.attr_example = "attribute";
}
myClass.prototype.do_something = function() {
  return "did something";
}

// create an instance of it, and modify as needed
var thing = new myClass();
thing.myMethod = function(arg) {
  return "myMethod stuff";
}

// ... so that this works as expected
console.log(thing.myMethod());
console.log(thing.do_something());
console.log(thing.attr_example);

当谈到在ColdFusion中做类似的事情时,我会陷入困境。我经常发现自己想做这样的事情:

<cfscript>
  // thing.cfc contains a normal cfcomponent definition with some methods
  var thing = createObject("component","Thing");
  function formattedcost() {
    return "#LSCurrencyFormat(this.cost)#";
  }
  thing.formattedcost = formattedcost;
</cfscript>
<cfoutput>
  #thing.formattedcost()#
</cfoutput>

让我们假设对于这个问题,将“formattedcost”添加为Thing类的方法是没有意义的,因为它纯粹是表示性的。我们还假设在#LSCurrencyFormat(thing.cost)#标记中简单地使用<cfoutput>也不够,因为我们需要由模板系统(在这种情况下为胡须)来评估Thing的实例。更进一步,我想避免创建另一个.cfc文件只是为了扩展我的Thing类来添加几个方法。

我该怎么办?这种编程风格在ColdFusion中是否可行?

1 个答案:

答案 0 :(得分:7)

是的,你可以这样做:

Thing.cfc

<cfcomponent output="false" accessors="true">
    <cfproperty name="cost" type="numeric">
    <cffunction name="init" output="false" access="public" 
        returntype="any" hint="Constructor">
        <cfargument name="cost" type="numeric" required="true"/>
        <cfset variables.instance = structNew()/>
        <cfset setCost(arguments.cost)>
        <cfreturn this/>
    </cffunction>
</cfcomponent>

test.cfm

<cfscript>
  // thing.cfc contains a normal cfcomponent definition with some methods
  thing = new Thing(725);
  function formattedcost() {
    return "#LSCurrencyFormat(getCost())#";
  }
  thing.formattedcost = formattedcost;
</cfscript>
<cfoutput>
  #thing.formattedcost()#
</cfoutput>

结果

$725.00