对不起,这个短语。我找不到更好的描述方式。但是我的问题如下:
我有3个cfc,即settings.cfc,prices.cfc和helpers.cfc。这些cfc扩展了第4个cfc controller.cfc。helper.cfc如下:
<cfcomponent extends="Controller">
<cffunction name="formatCurrency">
<cfset formattedCurrency = 1 />
<cfreturn formattedCurrency>
</cffunction>
<cffunction name="processTemplateVariables">
<cfargument name="templateText" default="defaultText" >
<cfset formatCurrency() />
<cfreturn formattedCurrency >
</cffunction>
</cfcomponent>
settings.cfc有一个setApplicationVariables方法,可用来设置应用程序级别的变量。在此cfc中,我创建了一个helpers.cfc对象,并将该对象放入应用程序范围。settings.cfc如下:
<cfcomponent extends="Controller">
<cffunction name="setApplicationVariables">
<cfset application.helpers = createObject("component","controllers.Helpers") />
</cffunction>
</cfcomponent>
在应用程序启动时会调用settings.cfc,这反过来会创建一个helpers.cfc对象,并将其放入应用程序范围。
我们在controller.cfc中创建对ProcessTemplateVariables方法的引用,如下所示:
<cfcomponent extends="Wheels">
<cfset getFormattedCurrency = application.helpers.processTemplateVariables >
</cfcomponent>
在prices.cfc中,我们使用此引用来调用function processTemplateVariables
。但是它does not call the function formatCurrency
是从processTemplateVariables内部调用的,并引发错误“变量formatCurrency未定义”。
但是,如果我使用application.helpers.processTemplateVariables(templateText="someText")
,它可以工作。
当我使用cfinvoke作为波纹管时,它也起作用:
<cfinvoke method="processTemplateVariables" component="controllers.helpers" templateText="someText" returnvariable="content">
prices.cfc如下:
<cfcomponent extends="Controller">
<cffunction name="index">
<!--- does not work, throws 'the formatCurrency() variable is undefined' --->
<cfdump var="#getFormattedCurrency("someText")#"><cfabort>
<!--- works --->
<cfinvoke method="processTemplateVariables" component="controllers.helpers" templateText="someText" returnvariable="content">
<!--- works --->
<cfset application.helpers.processTemplateVariables("someText") />
</cffunction>
</cfcomponent>
我不确定为什么使用引用不起作用。对先前的混乱感到抱歉,但是您的评论使我更加深入,我发现这是造成这种情况的罪魁祸首。有什么办法可以参考一下,这很酷吗?
更新:
此博客条目(由Adam Cameron撰写)具有更好的描述。总结一下:
..它将方法从CFC中拉出,因此它将在调用代码而不是CFC实例的上下文中运行。根据方法中的代码,这可能重要,也可能不重要。
在您的特定情况下,这确实很重要。该函数具有依赖项formatCurrency
,而该依赖项在调用页面的“上下文”中不存在,因此这就是您收到“未定义”错误的原因。
(摘自评论)
是的,我很确定您不能这样做。每个函数都被编译成一个单独的类:特别是一个静态内部类。(如果转储不带括号的函数名称,则可以看到内部类名称,即#application.helpers.formatCurrency#
)。换句话说,它与任何特定实例(通过扩展)与其他函数都断开连接。
创建组件实例时,所有功能都存储在其variables
作用域内。因此,当您从实例内部调用“ processTemplateVariables”时,它可以通过组件的variables
作用域访问其他功能。当您的代码创建对该函数的引用时,您实际上获得的是与父实例完全断开的连接application.helpers
。因此,它将无法访问任何其他功能。因此,为什么会出现“未定义”错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句