简体   繁体   English

从一个类调用另一个类的函数

[英]Calling a function from one class, from another

I'm having a slight issue with ActionScript 3 and I have come here to ask for some help. 我在使用ActionScript 3时遇到了一个小问题,我来这里是为了寻求帮助。

I have two classes. 我有两节课。 One called Sledge and one called Sock , there is also the document class called Main . 一个叫做Sledge ,另一个叫做Sock ,还有一个叫做Main的文档类。

My issues are as follows: 我的问题如下:

  • Inside of Sledge , I call a function that is defined inside of the Main document class. Sledge内部,我调用在Main文档类内部定义的函数。 How would I go about telling the class to go to the document class and run that function? 我将如何告诉类去文档类并运行该函数? Would this also be the same for other classes or just for the document class? 其他类还是仅文档类也一样吗?

  • Inside Sledge , I have the following statement: if(hitTestObject(sock.myHitArea)) { /* somecode*/ } Sledge内部,我有以下语句: if(hitTestObject(sock.myHitArea)) { /* somecode*/ }

    sock is an instance of another seperate class, and by this point has already been created. sock是另一个单独类的实例,到目前为止,已经创建了它。 However when I try and run this I am told it is not defined. 但是,当我尝试运行此程序时,系统会告诉我它没有定义。 How would i go about solving this? 我将如何解决这个问题?

There's some ambiguity issues with how you expressed your question. 您如何表达问题有些模棱两可的问题。 It would help if you posted a short form of the code for the problem. 如果您发布该问题的简短代码,将很有帮助。

However, I'll try to answer the first question: 但是,我将尝试回答第一个问题:

Inside of Sledge, I call a function that is defined inside of the Main document class. 在Sledge内部,我调用在Main文档类内部定义的函数。 How would I go about telling the class to go to the document class and run that function? 我将如何告诉类去文档类并运行该函数?

You would want to pass the Main class to the Sledge class or use events which is preferable. 您可能希望将Main类传递给Sledge类或使用更可取的事件。 If pass the class it will look like this... 如果通过课程,它将看起来像这样...

class Sledge {
   private var main:Main;
   function Sledge(main:Main) {
      this.main = main;
   }
   function doSomething():void {
     main.runSomeFunction();
   }
}

Or if using events: 或者,如果使用事件:

class Main {
private var sledge:Sledge;
   function Main() {
      sledge = new Sledge();
      sledge.addEventListener("mainDoSomething", doSomething);
   }
   private function doSomething(e:Event):void {
     // .... do stuff
   }
}
class Sledge extends EventDispacter {
   function Sledge() {
   }
   public function doSomething():void {
     dispatchEvent(new Event("mainDoSomething"));
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM