我认为您可能对继承的工作方式感到困惑;特别是 Parent 和 Child 类之间的关系。
父类可以以子类可以使用的方法和属性的形式公开行为,这里有一个非常简单的例子:
public class Parent {
// Constructor for the Parent Class.
public function Parent() {
}
protected function sayHello() : void {
trace("Hello!");
}
}
我们现在可以创建这个 Parent 类的子类,它将获得 Parent 的可见行为(函数和属性):
public class Child extends Parent {
// Constructor for the Child Class.
public function Child() {
// Call the 'parent' classes constructor.
super();
// This child class does not define a function called "sayHello" but
// the Parent class which this Child class extends does, and as a result
// we can make a call to it here. This is an example of how the child Class
// gains the behaviours of the Parent class.
this.sayHello();
}
public function sayGoodbye() : void {
trace("Goodbye!");
}
}
现在,这种关系(子类可以访问它们扩展的父类的功能和属性)仅以一种方式起作用。也就是说,Parent 类不知道其子类可能选择声明的函数和属性,因此,以下代码将不起作用:
public class Parent {
public function Parent() {
// Trying to call the sayGoodbye() method will cause a compilation Error.
// Although the "sayGoodbye" method was declared in the Child class, the
// Parent Class has no knowledge of it.
this.sayGoodbye();
}
}
现在,让我们看看我们如何解决您尝试从父类访问属于 FLA 中的实例的 TextField 的问题:
// it is important to note that by extending the MovieClip class, this Parent Class now
// has access to all the behaviours defined by MovieClip, such as getChildByName().
public class Parent extends MovieClip {
// This is a TextField that we are going to use.
private var txtName : TextField;
public function Parent() {
// Here we are retrieving a TextField that has an instance name of txtName
// from the DisplayList. Although this Parent Class does not have a TextField
// with such an instance name, we expect the children that extend it to declare
// one.
txtName = this.getChildByName("txtName") as TextField;
// Check to see if the Child class did have an TextField instance called
//txtName. If it did not, we will throw an Error as we can not continue.
if (txtName == null) {
throw new Error("You must have a TextField with an instance name of 'txtName' for this Parent Class to use.");
}
// Now we can make use of this TextField in the Parent Class.
txtName.text = "Hi my name is Jonny!";
}
}
您现在可以在您的 FLA 中拥有尽可能多的实例,这些实例通过链接扩展此父类。您只需要确保他们有一个实例名称为“txtName”的 TextField,这样父类就可以完成它的工作。
希望这可以帮助 :)