在初始化函数后从THIS范围获取值(CFC内部的持久性)

时间:2019-07-01 18:22:15

标签: coldfusion cfml lucee

我正在启动这样的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的名称,Google很难获得详细信息。我以为它将在整个CFC的生命中持续存在,但显然不是吗?

我当然可以做类似

的操作
var self = application[this.title]; // or application.mycfc

也许甚至

this = application[this.title];

在我不想每次都输入application.mycfc的情况下获取/设置的函数。

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

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

1 个答案:

答案 0 :(得分:4)

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之类的共享范围应该在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

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