我正在启动这样的 CFC。
<cfscript>
lock scope="application" timeout="5" {
application.mycfc = new mycfc();
}
writeOutput(application.mycfc.readVars());
</cfscript>
Run Code Online (Sandbox Code Playgroud)
在 CFC 中,我正在设置一些属性。
component output="false" accessors="true" {
property name="title";
property name="foo";
this.title = "mycfc";
function init() {
this.foo = "bar";
// I can now properly read this.title, or this.foo.
return this;
}
function readVars() {
// Here, I can read this.title, from the constructor space, but I can't
// read this.foo. It's just blank (because the default value of the
// `default` attribute of `property` is "")
}
}
Run Code Online (Sandbox Code Playgroud)
由于实现(在应用程序中缓存),我可以改用application.mycfc.fooin readVars().
由于this名称的关系,很难在谷歌上搜索详细信息。我以为它会在 CFC 的整个生命周期中持续存在,但显然不是?
我当然可以做类似的事情
var self = application[this.title]; // or application.mycfc
Run Code Online (Sandbox Code Playgroud)
或者甚至
this = application[this.title];
Run Code Online (Sandbox Code Playgroud)
在我想要获取/设置而不application.mycfc每次输入的功能中。
只是想确保我没有做错什么,或者重新发明轮子。
在我的实际实现中,我从数据库中提取行来填充结构。
ColdFusion 组件 (.cfc) 中的范围:
this
是公共范围,从任何地方读/写
properties
是一个神奇的范围,只能通过访问器(又名 getter/setter)从任何地方读取/写入
variables
是私有范围,仅在您的组件内读/写
所有这些范围都可以共存,但this.x与property name="x"!
由于您使用的是带有 的组件accessors="true",因此您的所有property字段只能通过 getter 读取并通过 setter 写入。因此,如果您想编写您的title属性,请使用setTitle("mycfc");代替this.title = "mycfc";。这同样适用于foo财产。使用setFoo("bar");代替this.foo = "bar";。如果要读取属性,请使用application.mycfc.getTitle()和application.mycfc.getFoo()。如果要在运行时设置属性,请使用application.mycfc.setTitle("something"). 请注意,写入共享范围(例如application应该在 a 中发生)cflock以避免竞争条件(线程安全)。
如果您根本不需要访问器,您可以简单地使用公共字段代替(accessors此处缺少,即设置为 false):
component output="false" {
this.title = "mycfc";
this.foo = "";
function init() {
this.foo = "bar";
return this;
}
function readVars() {
return this;
}
}
application.mycfc = new mycfc();
writeOutput(application.mycfc.title); // mycfc
writeOutput(application.mycfc.foo); // bar
application.mycfc.title = "something";
writeOutput(application.mycfc.title); // something
writeOutput(application.mycfc.foo); // bar
Run Code Online (Sandbox Code Playgroud)
通常不建议使用公共字段,因为它们会破坏封装。
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |