as3继承变量
我有一个基类“车辆”和一个派生类“汽车”。
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”的值?我应该如何正确实施这个?
I have a base class "Vehicle" and a derived class "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();
}
}
}
Basically, I want to set a vehicle property in Car's constructor, call Vehicle's constructor with super() and have Vehicle do something based on myVar. But this is the output i get:
car pre: null
car post: car
vehicle: vehicle
Why does myVar not keep the value of "car" when the base class constructor is called? How am I supposed to implement this correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
变量初始化在超类中。在您实际调用
super();
之前,它不会被初始化。这就是为什么您应该在构造函数中执行任何其他操作之前始终调用super()
。事实上,在其他一些语言(如 Java)中,对 super() 的调用只允许作为子类构造函数中的第一个语句。但是,您应该考虑在构造函数中使用初始化参数,而不是在声明中设置值 - 这是执行您打算执行的操作的更优雅且可维护的方式。
分别。
另外,您始终可以调用 new Car("Porsche"); 或类似的名称 ;)
PS 旁注:ActionScript 中的命名约定建议对两个包使用以小写字母开头的名称和方法。
The variable initialization is in the super class. It won't be initialized until you actually call
super();
. This is why you should always callsuper()
before doing anything else in the constructor. In fact, in some other languages, like Java, calls tosuper()
are only allowed as the first statement within subclass constructors.However, you should consider using an initialization parameter in your constructor instead of setting the value in the declaration - it is the more elegant and maintainable way of doing what you intend to do.
resp.
plus, you can always call
new Car("Porsche");
, or something like that ;)P.S. On a side note: Naming conventions in ActionScript recommend using names starting with a lower case letter for both packages and methods.