0

So - I have a bunch of instances of a class and there's a function I want to call on all of them. I'm wondering if rather than loop through every instance that I have, is there some way I can declare a function on the class that when called runs on each instance? For example - if my class looks like this:

public class MyClass{

    public var variable:String = "";

    public function MyClass(){}

    public function myFunction():void{
       this.variable = "BLORE";
    }
}

and I have a bunch of these:

var class1:MyClass = new MyClass();
var class2:MyClass = new MyClass();

is there a way I can call MyClass.myFunction() and have it called on all of my instances?

I don't know if I'm explaining this well...but there it is. I'd love any suggestions you have that don't just involve "put your instances in an array or vector and loop through them like a real man."

4

2 回答 2

1

这是一个如何完成此操作的快速示例:

package {
    public class Example {
        public static var instances:Array;

        public function Example() {
            if ( !instances ) {
                instances = [];
            }
            instances.push( this );
        }

        public static function setPropertyOnAll( property:String, value:Object ):void {
            var l:uint = instances.length;
            for ( var i:uint = 0; i < l; i++ ) {
                instances[i][property] = value;
            }
        }
    }
}

基本上,您的类中有一个静态数组,并在实例化时将该类的每个实例推入该数组。然后,您只需遍历数组并更改属性。

请记住以下几点:

  • property如果不存在,则没有错误处理。因此,请确保您传入的属性setPropertyOnAll实际上是一个属性,或者您添加某种错误检查以确保。
  • 将每个实例保存到数组中将使它们没有资格进行垃圾收集。这很糟糕,很明显。如果您这样做,您将需要创建一种从数组中删除每个实例的方法,即使每次都必须手动完成。我没有这样做是因为不可能知道如何/何时运行它或者你的类结构是什么样的,所以这将是你需要弄清楚的事情。您不想让他们没有资格进行垃圾收集
于 2013-08-07T21:08:20.677 回答
1

这就像使用一个static函数一样简单,该函数使用一个static Array对该类的所有实例的引用。

每次调用类构造函数创建新实例时,都需要将实例的引用添加到Array

arrayOfInstances.push(this);

然后您的static函数将循环数组并执行您需要的任何操作。

不要忘记添加一些静态方法来删除所有引用,Array以便垃圾收集器可以从内存中清除这些对象。

于 2013-08-07T19:41:55.347 回答