首页 > 解决方案 > 在 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每次输入的功能中。

只是想确保我没有做错什么,或者重新发明轮子。

在我的实际实现中,我从数据库中提取行来填充结构。

标签: coldfusioncfmllucee

解决方案


ColdFusion 组件 (.cfc) 中的范围:

  • this
    是公共范围,可以从任何地方读/写

  • properties
    是一个神奇的作用域,只能通过访问器(又名 getter/setter)从任何地方读/写

  • variables
    是私有范围,仅在您的组件内读/写

所有这些范围都可以共存,但this.xproperty 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

通常不建议使用公共字段,因为它们会破坏封装。


推荐阅读