AS3从另一个类调用Main.as文档类的函数函数、文档、Main、as

2023-09-08 14:26:17 作者:稳步沙场

我相信这是一个普遍的问题,但我无法找到我所需要的确切答案。我只需要访问该Main.as文档类创建一个或多个功能。我尝试了好几种方法,他们似乎并没有工作。这里有一个例子,我试过了。

anotherClass.as //这需要访问功能Main.as

 包COM
{
进口主;

公共类anotherClass
    {
私人VAR stageMain:主;

公共职能anotherClass()
        {
    //试图调用一个函数Main.as称为languageLoaded。没有工作!
        stageMain.languageLoaded(英语);
    //在Main.as languageLoaded是公共职能

        }

    }
}
 

解决方案

在清洁的方法是简单地传递一个参照的类要构造能够访问它。

例如,你的 AnotherClass 可能是这样的:

 类AnotherClass
{
    私人VAR _main:主;

    公共职能AnotherClass(主:主)
    {
        _main =为主;
        _main.test(); // 成功!
    }
}
 
八 Python 玩转模块,和文件的引用

和你的主类:

 类主
{
    公共函数main()
    {
        VAR另:AnotherClass =新AnotherClass(本);
    }

    公共功能测试():无效
    {
        跟踪(成功!);
    }
}
 

I am sure this is a popular question but I can't find the exact answer I need. I simply need to access a function or functions created in the Main.as document class. I have tried several methods and they do not seem to work. Here is one example I tried.

anotherClass.as // This needs to access functions Main.as

package com 
{
import Main;

public class anotherClass
    {
private var stageMain:Main;

public function anotherClass() 
        {
    // tries to call a function in Main.as called languageLoaded. NO WORK!  
        stageMain.languageLoaded("English");
    // in the Main.as languageLoaded is a public function

        }

    }
}

解决方案

The cleaner way is to simply pass a reference to Main to the constructor of the class you want to be able to access it.

For example, your AnotherClass could look like this:

class AnotherClass
{
    private var _main:Main;

    public function AnotherClass(main:Main)
    {
        _main = main;
        _main.test(); // Success!
    }
}

And your main class:

class Main
{
    public function Main()
    {
        var another:AnotherClass = new AnotherClass(this);
    }

    public function test():void
    {
        trace("Success!");
    }
}