上面有人问,“舞台为什么要全球化?” 答:我认为它不应该是全局的,但这里有一个简单的用例,其中全局访问舞台非常有用:找到可用的像素来布局(位置、大小) DisplayObject 和/或其之前的视觉资产被添加到显示列表中。
有时我的布局类在添加到显示列表之前没有扩展DisplayObject
并获取对 DisplayObjects 的布局的引用-因此还没有它自己的属性。使用下面的方法,在主文档类具有属性并调用
后,我总是可以随时知道当前可用的像素DisplayObject
stage
stage
GlobalReference.global.stage = stage;
var screenWidth : uint = GlobalReference.global.stage.stageWidth;
var screenHeight : uint = GlobalReference.global.stage.stageHeight;
!!警告 !!全局变量很危险且容易误用
我添加了对“全局”对象的引用(非常仔细和深思熟虑),以便我可以从任何类访问它们——特别是能够在闭包或匿名函数中访问它。闭包不需要调用静态 getter,因为它们已经在全局范围内。
package com.appcloud9.utils
{
public class GlobalReference
{
public static function get global() : Object
{
// may be superstition, but I *think* that assigning the function
// to a var is better for garbage collection later
var getGlobal : Function = function() : Object
{
return this;
};
return getGlobal();
}
}
}
// usage examples :
// I call this in my main document class on the Event.EXIT_FRAME event :
GlobalReference.global.stage = stage;
// later in a closure
var signalLightsOut = new Signal();
signalLightsOut.add( function() : void
{
trace( stage ); // [object Stage]
} );
// later in a constructor - before the class has a stage of it's own
public function MyConstructor()
{
trace( stage ); // null
trace( GlobalReference.global.stage ); // [object Stage]
/* note : it is usually best and fully adequate to wait until a class extending
DisplayObject has its own stage : after Event.ADDED_TO_STAGE and then
Event.EXIT_FRAME it is guaranteed. */
}