ActionScript 通过更改公共变量来调用私有函数?

发布于 2024-09-05 16:18:06 字数 168 浏览 10 评论 0原文

我以前从未尝试过这样做,所以我的头有点晕。我希望在 myClass 自定义类中有一个名为 enabled 的公共布尔值。如果调用它进行更改,我如何从更改中触发函数?

我应该向我的变量添加一个 Event.CHANGE 事件监听器吗?我可以这样做吗?或者有更标准的方法吗?

i've never tried to do this before, so my head a swimming a bit. i'd like to have a public boolean called enabled in myClass custom class. if it's called to be changed, how do i trigger a function from the change?

should i add an Event.CHANGE event listener to my variable? can i do that? or is there a more standard way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清风挽心 2024-09-12 16:18:06

我们通常使用属性来实现这一点。
属性就像外部的公共变量一样——您可以设置instance.enabled = true; 等等。但是您可以将属性定义为类的getter 和/或setter 函数。
它们是在值更改时执行自定义逻辑的完美场所。

例如:

public class CustomClass {
    private var _enabled:Boolean = false;

    public function set enabled(value:Boolean):void {
        trace('CustomClass.enabled is now', value);
        this._enabled = value;
    }

    public function get enabled():Boolean {
        trace('CustomClass.enabled was retrieved');
        return this._enabled;
    }
}

请注意,它们不能与您的私有变量具有相同的名称,并且您不需要同时定义它们。实际上,您甚至不需要 setter/getter 变量。您可以像任何函数一样使用它们——它们只是为您提供不同的语法。
例如:

var object:CustomClass = new CustomClass();
object.enabled = false;
if (object.enabled) {
    ...
}

它们非常适合公开一个简单的 API,让您在类的内部结构必须更改时无需重写外部代码。

关于 getter设置器

We usually use properties for that.
Properties are just like public variables for the outside -- you can set instance.enabled = true; and so forth.. But you define properties as getters and/or setters functions for the class.
They are the perfect place for custom logic to be executed on value changes.

For example:

public class CustomClass {
    private var _enabled:Boolean = false;

    public function set enabled(value:Boolean):void {
        trace('CustomClass.enabled is now', value);
        this._enabled = value;
    }

    public function get enabled():Boolean {
        trace('CustomClass.enabled was retrieved');
        return this._enabled;
    }
}

Note that they can't have the same name as your private variable and you don't need both of them defined. Actually, you don't even need a variable for a setter/getter. You could use them just like any function -- they just supply you with a different syntax.
For example:

var object:CustomClass = new CustomClass();
object.enabled = false;
if (object.enabled) {
    ...
}

They are great to expose a simple API, keeping you from rewriting outside code if the class' internals have to change.

AS3 Reference on getters and setters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文