我目前正在学习使用单独的.as文件和类,但在阅读了很多内容之后,所有内容似乎与我所阅读的内容有所不同。 我发布这个问题是为了学习,而不仅仅是为了使代码工作。 这里的例子是我真实项目的测试,简化再现。
我的文件“MyApp.fla”有1个框架,形状为背景,DocumentClass设置为“MyApp”。 该库拥有一个带有另一个背景形状的1帧符号“Page1”,其类别设置为“Page1”
MyApp.as:
package {
trace("1: DocumentClass file, before class");
import flash.display.MovieClip;
public class MyApp extends MovieClip {
trace("2: DocumentClass file, in the class")
public var setting1:int = 2; //this is a variable which i want to be accesible to other classes, so to the pages being loaded
private var currentPage:MovieClip; //I wanted to create this var in the constructor, but I'm afraid something will explode again :<
public function MyApp() {
trace("3: DocumentClass file, in constructor function");
currentPage = new Page1;
addChild(currentPage);
}
}
}
Page1.as:
package {
trace("4: Page1 file, before class");
import flash.display.MovieClip;
public class Page1 extends MovieClip {
trace("5: Page1 file, in class, before constructor");
public function Page1() {
trace("6: Page1 file, in constructor")
trace(setting1) //According to everything i read this should work since setting1 is public, but it gives me: "1120 Acces of undefined property setting1" so i commented this out for the output.
trace(root);
trace(stage); //both trace null since i haven't used addChild() yet, but now i dont know how to try to reference my variables through the main timeline.
}
}
}
输出:
虽然两个背景形状都按预期显示,但生成的输出完全不符合我的预期。我的主要问题是:为什么我的痕迹没有订购1-6?
我的下一个问题:为什么Page1()构造函数不能引用public var setting1?,我假设我可以通过将setting1作为参数传递给Page1()构造函数来解决,但我出于学习目的而避免这种情况。
答案 0 :(得分:5)
setting1是父对象中的变量,而不是您尝试从中调用它的对象。这就行不通。
trace(this.parent.setting1);
trace(MovieClip(parent).setting1);
使用上述其中一个替换它应该有效,因为您正在调用引用它的变量形式,即父类。
订单的原因是:
5 - the class itself is imported before anything else
4 - while the class loads, it checks for additional imports
2 - after it finished importing all classes, it loads its own class
1 - again, while the class loads it check for imports
3 - after everything is loaded, it's free to run the main function of the class
6 - same as 3, but the child always walks behind the parent
请记住,在面向对象的编程中,它需要在尝试对它们执行任何操作之前加载所有对象(或类)。想象一下,如果subclass.as有一个变量,而class.as在加载之前就试图访问它。
希望这会有所帮助:)。如果您需要更多详细信息,请随时向我们汇总。