【问题标题】:as3 inherited variablesas3 继承变量
【发布时间】:2012-01-26 22:36:02
【问题描述】:

我有一个基类“Vehicle”和一个派生类“Car”。

package Game
{

    public class Vehicle
    {
        public var myVar = "vehicle";

        public function Vehicle()
        {
            trace("vehicle: " + myVar);
            DoSomethingWithMyVar();
        }

    }

}

package Game
{

    public class Car extends Vehicle
    {

        public function Car()
        {
            trace("car pre: " + myVar);
            myVar = "car";
            trace("car post: " + myVar);
            super();
        }

    }

}

基本上,我想在 Car 的构造函数中设置一个车辆属性,用 super() 调用 Vehicle 的构造函数,并让 Vehicle 基于 myVar 做一些事情。但这是我得到的输出:

car pre: null
car post: car
vehicle: vehicle

为什么调用基类构造函数时,myVar 不保留“car”的值?我应该如何正确实现这一点?

【问题讨论】:

  • 你能分享更多关于实际目标的信息吗?

标签: actionscript-3 variables inheritance super


【解决方案1】:

变量初始化在超类中。在您实际调用super(); 之前,它不会被初始化。这就是为什么在构造函数中执行任何其他操作之前,您应该始终调用super()。事实上,在其他一些语言中,比如 Java,对 super() 的调用只允许作为子类构造函数中的第一条语句。

但是,您应该考虑在构造函数中使用初始化参数,而不是在声明中设置值 - 这是执行您打算执行的操作的更优雅和可维护的方式。

package game
{   
    public class Vehicle
    {
        public var myVar: String;

        public function Vehicle ( type:String = "vehicle" ) 
                             // new Vehicle() traces "vehicle"
        {
            trace("vehicle: " + type);
            myVar = type;
            doSomethingWithMyVar();
        }
    }
}

分别

public function Car ( type: String = "car" )
                             // new Car() traces "car"
{
    super( type );
}

另外,您可以随时拨打new Car("Porsche");,或类似的电话;)

附:附带说明:ActionScript 中的命名约定建议对包和方法使用以小写字母开头的名称。

【讨论】:

  • 谢谢,我在末尾而不是开头使用 super() 的原因是因为初始化的东西。我将初始化例程与构造函数分开。我不知道命名约定(尽管我应该意识到所有现有的方法都是小写的......)。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-09
  • 2014-10-06
  • 2016-06-01
  • 1970-01-01
  • 2018-08-13
  • 2012-11-05
相关资源
最近更新 更多