【问题标题】:Where can i find a good article on cross-class communication for AS3?我在哪里可以找到一篇关于 AS3 跨类通信的好文章?
【发布时间】:2013-01-17 20:12:04
【问题描述】:

我正在寻找一个很好的教程,其中概述了您如何在外部类之间进行通信以及如何正确地确定类的范围等,但我正在努力寻找一篇文章。有没有人对我可以学习这些概念的教程有什么建议?

【问题讨论】:

  • 什么是外部类?如果您指的是在运行时加载的类,您需要实现一个接口以便与加载的数据进行交互。

标签: actionscript-3 oop


【解决方案1】:

听起来您正在寻找有关一般面向对象编程的教程。 http://active.tutsplus.com/tutorials/actionscript/as3-101-oop-introduction-basix/

作为一个概述 - 要与大多数面向对象语言中的不同类进行通信,您可以:

从该类继承。 (在 AS3 中使用“扩展”关键字)

class Square {
    var x, y, width, height;
}

class Rectangle extends Square{
    function changeDimensions( newWidth, newHeight ):void {
        super.width = newWidth;
        super.height = newHeight;
    }
}

将该类的实例作为类的属性(参见http://en.wikipedia.org/wiki/Has-a)。

class Tire {
    var radius, tred;
}

class Car {
    var width, depth;
    var make;
    var leftBackTire:Tire;
    var rightBackTire:Tire;
    var leftFrontTire:Tire;
    var rightFrontTire:Tire;
}

将外部类的实例作为函数参数传递给您的类的函数。

class Person {
    var position;
}

class Treadmill {
    function movePerson( personToMove:Person ):void {
        personToMove.x += 5;
    }
}

创建外部类的全局实例(在 any 类的范围之外)并在任何地方访问它。

class World {
    var inhabitance;
}

var earth:World = new World();

class InhabitanceCalculator {
    function calcuateEarthInhabitance():void {
        earth.inhabitance = 3000000000;
    }
}

(特别是 AS3)使用预定义的事件系统,您的类在其中注册要为特定事件调用的函数,外部类将其传输给任何收听的人。

class Scoreboard extends EventDispatcher {
     var points = 0;
     Scoreboard(player:Player) {
         player.addEventListener("PlayerKilledEnemy", onPlayerKilledEnemy);
     }
     function onPlayerKilledEnemy():void {
         points += 1;
     }
}

class Player extends EventDispatcher {
    function killEnemy():void {
        //Aaaah!
        dispatchEvent( new Event("PlayerKilledEnemy") );
    }
}

请注意,我没有在变量/类/函数中添加“public”关键字。您需要将其添加到您希望在课程之外访问的任何内容。

【讨论】:

    【解决方案2】:

    我还会花一些时间查看自定义事件。如果使用得当,它们可以在 AS3 中的类之间提供极其通用的管道。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-31
      • 2011-08-06
      • 2018-06-16
      • 2012-02-27
      • 1970-01-01
      • 2023-03-09
      • 2013-03-17
      • 1970-01-01
      相关资源
      最近更新 更多