2011-04-19 4 views
3

내 질문에 대한 예가 나와 있습니다. 자바 스크립트에서 나는 이런 식으로 할 수있는 데 익숙해졌습니다.ColdFusion의 클래스, 인스턴스 및 메소드에 대해 혼동을 야기합니다.

// 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"를 추가 할 수 이해가되지 않습니다,의이 질문에 대한 것을 가정 해 봅시다. <cfoutput> 태그에서 #LSCurrencyFormat(thing.cost)#을 단순히 사용한다고 가정하면 템플릿 시스템 (이 경우에는 콧수염)으로 평가하려면 Thing의 인스턴스가 필요하기 때문에 충분하지 않을 수도 있습니다. 더 나아가서, 나는 두 개의 메소드를 추가하기 위해 내 Thing 클래스를 확장하기 위해 또 다른 .cfc 파일을 작성하지 않아야한다.

어떻게해야합니까? ColdFusion에서 이러한 프로그래밍 스타일을 사용할 수 있습니까?

답변

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 
+0

당신을 감사합니다! 나는 거의 거기에 있었다고 생각한다! 그러나 이것은 '가하는 또 다른 질문은 무엇입니까? –

+0

유감스럽게도 CFC를 작성할 때 사용하는 보일러 코드입니다. 너는 필요 없어. – orangepips

+1

Hey @DustMason, @orangepips set 문은 내부 인스턴스 변수를 생성하므로 CFC 내부에 영구 데이터를 저장할 수 있습니다. 외부 응용 프로그램을 사용하지 않으려는 객체의 모든 메소드에서 사용할 수 있어야하는 변수에 사용하는 것이 좋습니다. –

관련 문제