“正确”的地方在哪里? AS3中初始化类变量的地方

发布于 2024-09-06 22:39:54 字数 409 浏览 6 评论 0原文

在类构造函数中初始化 AS3 类变量是否“更好”?或者当我在类的顶部声明它们时,我可以将它们初始化为默认值吗?我问这个问题是因为当有很多类变量时,在一个地方声明它们然后在另一个地方初始化它们似乎效率很低,而我可以轻松地在同一个地方执行这两个操作。其中一种选择比另一种更好,为什么?

谢谢!

例如:

在构造函数中初始化

class foo {
    var bar:Boolean
}

function foo():void {
    bar = true;
}

使用声明初始化

class foo {
    var bar:Boolean = true;
}

function foo():void {
}

Is it "better" to initialize AS3 class variables in the class constructor? Or can I just initialize them to their default value when I declare them at the top of my class? I ask because when there's a lot of class variables, it appears inefficient to declare them in one place and then initialize them in another when I could easily do both in the same place. It one option is better than the other, why?

Thanks!

eg:

initializing in constructor

class foo {
    var bar:Boolean
}

function foo():void {
    bar = true;
}

OR

initializing with the declaration

class foo {
    var bar:Boolean = true;
}

function foo():void {
}

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

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

发布评论

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

评论(2

把梦留给海 2024-09-13 22:39:54

我个人建议在构造函数内进行初始化,原因有两个:

  1. 您无法初始化依赖于在构造之前已创建的其他 var 对象的对象。
  2. 当初始化代码按照适当的程序进行时,可以更轻松地找到和理解初始化代码。尤其是当你(我)重新投入到我已经好几个月没有开过的大课中时。

I personally recommend initialization inside the constructor for two reasons:

  1. You cannot initialize objects that depend on other var objects having already been created before construction.
  2. It's easier to locate and understand initialization code when it's properly procedural. Especially when you (I) dive back into big classes I haven't opened for months.
一身仙ぐ女味 2024-09-13 22:39:54

我个人也不这么做!我喜欢创建一个“init”函数来初始化所有内容。这意味着如果我需要将实例重置为其默认值,我可以随时调用 init 方法。

Personally I don't do either! I like to create an "init" function that initializes everything. That means if I need to reset the instance to its default, I can just call the init method at anytime.

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