2012-02-02 48 views
0

我需要在Coldfusion 8中实现与JavaScript的call()或apply()函数类似的功能。我需要一种方法来动态绑定我的'this'函数被调用。缺少在参数列表中的上下文中手动传递,是否有任何其他方式来执行此操作?不幸的是,我很难在Google上搜索线索,因为我似乎无法搜索关键字“this”。在Coldfusion for JavaScript的调用()和apply()函数中相当于

<!--- component A ---> 
<cfcomponent> 
    <cffunction name="init"> 
     <cfset this.value = "My name is A"> 
     <cfreturn this> 
    </cffunction> 

    <cffunction name="setDelegate"> 
     <cfargument name="delegate"> 

     <cfset this.delegate = delegate> 
    </cffunction> 

    <cffunction name="runDelegate"> 
     <cfoutput>#this.delegate()#</cfoutput> 
    </cffunction> 
</cfcomponent> 

<!--- component B ---> 
<cfcomponent> 
    <cffunction name="init"> 
     <cfset this.value = "Hello, I am B"> 
     <cfreturn this> 
    </cffunction> 

    <cffunction name="call"> 
     <cfoutput>#this.value#</cfoutput> 
    </cffunction> 
</cfcomponent> 

<!--- main cfm ---> 
<cfset mrA = createObject('component', 'A').init()> 
<cfset mrB = createObject('component', 'B').init()> 

<cfset mrA.setDelegate(mrB.call)> 

<!--- I want to return "Hello, I am B", ---> 
<!--- but it's going to output "My name is A" in this case ---> 
<cfoutput>#mrA.runDelegate()#</cfoutput> 

在上面的例子中,“这个”上下文属于A,但我要绑定的上下文到B以利用B的属性。

只需将mrB传入call()函数即可在JavaScript中执行此操作: mrA.runDelegate.call(mrB);这会将'this'上下文设置为mrB而不是mrA。

+0

原谅我,但我没有按照你的问题。如果你举了一个你想要完成的事情的例子,这可能会有所帮助。 – rip747 2012-02-02 14:55:29

+0

我已经添加了一些示例代码来阐明我试图实现的内容 – xess 2012-02-03 01:56:45

回答

0

我并不认为这是可能的,因为这个范围是CFC实例的公共范围,取代上下文并非易事。然而,正如@ rip747所建议的,如果你对自己的想法稍微清楚一些,也许有办法做到这一点。

1

假设你正试图从一个给定的组件,你可能需要做一些像

<cfinvoke component="#this#" method="#methodToCall#"> 
    <cfinvokeargument name="#prop#" value="#someValue#" /> 
</cfinvoke> 

这将使用整个的“本”,并呼吁在组件的方法中动态地调用一个方法,所以你的上下文应该是完整的。

如果您只是以标准方式调用组件中的某个方法,那么“this”可以不做任何特殊处理。

为了给你一个更好的解决方案,我们需要知道你试图实现的是什么。

0

对不起,我想我已经明白了。我还应该与代表一起传递给上下文。我突然意识到当我想到如何在JavaScript中做到这一点时,我错过了一个论点。

<!--- Component A ---> 
<cfcomponent> 
    <cffunction name="init"> 
     <cfset this.value = "My name is A"> 
     <cfreturn this> 
    </cffunction> 

    <cffunction name="setDelegate"> 
     <cfargument name="delegate"> 
     <cfargument name="context"> 

     <cfset this.delegate = delegate> 
     <cfset this.context = context> 
    </cffunction> 

    <cffunction name="runDelegate"> 
     <cfoutput>#this.delegate()#</cfoutput> 
    </cffunction> 
</cfcomponent> 

<!--- component B ---> 
<cfcomponent> 
    <cffunction name="init"> 
     <cfset this.value = "Hello, I am B"> 
     <cfreturn this> 
    </cffunction> 

    <cffunction name="call"> 
     <cfoutput>#this.value#</cfoutput> 
    </cffunction> 
</cfcomponent> 

<!--- main cfm ---> 
<cfset mrA = createObject('component', 'A').init()> 
<cfset mrB = createObject('component', 'B').init()> 

<cfset mrA.setDelegate("call", mrB)> 

<cfoutput> 
    <cfinvoke component="#mrA.context#" method="#mrA.delegate#"></cfinvoke> 
</cfoutput> 
相关问题