我有两个名为Class1
和Class2
的课程。
我如何在Class1
中使用Class2
中的函数?
答案 0 :(得分:2)
要从类访问函数,您需要通过new
关键字创建它的实例(除非函数为static
)。可以在 Class2中创建此实例:
public class Class2
{
// The property holding your instance is defined here so you can access
// it within any method of this class, as this is defined at class-level
// rather than within a function (like the constructor).
private var class1:Class1;
/**
* Class2's constructor.
* (Called automatically when an instance of Class2 is created).
*/
public function Class2()
{
// Create an instance of Class1 and assign it to the class-level
// property "class1" (defined above).
class1 = new Class1();
// You can call methods of Class1 now, via class1.
class1.someMethod();
}
}
答案 1 :(得分:0)
有很多不同的方法可以做到这一点。
直接在类
上调用方法的Class1
class Class1{
public function Class1(){
var class2:Class2 = new Class2(); //create a new Class2 object
class2.CallMe(); //call the CallMe function on Class2, note the . to indicate CallMe is a property of Class2
}
}
的Class2
class Class2{
public function Class2(){ //class 2 constructor. This is always called when you create a new Object()
}
public function CallMe():void{ //note this function is public
trace("I'm class 2");
}
}
将ref传递给另一个类的函数
的Class1
class Class1{
public function Class1(){
var class2:Class2 = new Class2(this.CallBack); //create a new Class2 object
//note I didn't add () to the end of CallBack, I just used the function name
}
private function CallBack(aString:String):void{ //note we can use private here
trace(aString) //I'm from Class2
}
}
的Class2
class Class2{
public function Class2(aFunction:Function){ //class 2 constructor. Here we an accept the function
aFunction("I'm from Class2"); //note I can pass a string back to class1
}
}
您还可以在超类
上扩展类和调用方法的Class1
class Class1 extends Class2{
public function Class1(){
super.CallFromClass(); //I'm super
}
}
的Class2
class Class2{
public function Class1(){
}
public function CallFromClass():void{
trace("I'm super");
}
}
请查看此链接以进一步阅读: http://www.adobe.com/devnet/actionscript/articles/oop_as3.html
答案 2 :(得分:0)
// Main.as
package {
public class Main() {
public function Main() {
}
public function hello():void {
trace("Hello from class Main"):
}
}
}
//Hi.as
package {
public class Hi() {
private var _main:Main;
public function Hi() {
}
public function fromMain():void {
_main = new Main(); //initialize an object of class Main()
_main.hello(); //call methods
}
}
}
答案 3 :(得分:0)
如果function/property
的{{1}}'可见',则可以从Class2
拨打Class1
的{{1}}。对类的属性/方法的访问权限由特定属性控制,该属性可以包含以下值:function/property
检查this。
然后,如果它是“可见的”,你需要的只是引用类(访问Class1
属性/方法)或类的实例(访问internal (default),private,public,protected,...
属性/方法)