coldfusion - 在 init 函数后从 THIS 范围获取值(CFC 内的持久性)
问题描述
我正在启动这样的 CFC。
<cfscript>
lock scope="application" timeout="5" {
application.mycfc = new mycfc();
}
writeOutput(application.mycfc.readVars());
</cfscript>
在 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 "")
}
}
由于实现(在应用程序中缓存),我可以改为使用application.mycfc.foo
.readVars()
由于this
名称,很难谷歌详细信息。我以为它会在 CFC 的整个生命周期中持续存在,但显然不是?
我当然可以做类似的事情
var self = application[this.title]; // or application.mycfc
或者甚至可能
this = application[this.title];
在我想要获取/设置而无需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
应该发生在 acflock
中)以避免竞争条件(线程安全)。
如果您根本不需要访问器,则可以简单地使用公共字段(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
通常不建议使用公共字段,因为它们会破坏封装。
推荐阅读
- rest - 在 API 网关中为 REST API 设置 $default 路由
- swift - 在只知道其名称的类上运行方法
- excel - Excel vba 编码(搜索然后从不同的工作表复制和粘贴
- javascript - 如何将“Access-Control-Expose-Headers”添加到 POST /login 端点?
- python - 你可以在 discord.py 中等待多个事件吗?
- python - 这是使用“self__attr__”的“正确”方式吗?
- python - Python selenium web-driver:从下拉列表中选择值(无此类元素异常)
- android - 如何在 Android 的同一应用程序中使用 WebView 处理导航
- sql-server - 通过考虑展望日来分组日期
- postgresql - 具有时区偏移(澳大利亚/悉尼)的 PostgreSQL 格式时间戳作为 JSON/字符串