对象中的对象

Objects within Objects

我的图书馆中有一个名为 Bottle 的对象。 Bottle 由 "Glass" 和 "Cap" 个实例组成。我的库中还有两个符号,分别是 CapGlass

当我点击 Bottle 的盖子时,它说这个对象是 class Cap,当我点击玻璃时,它说它是类型Glass。这些对象中的每一个都有基数 class flash.display.MovieClip.

然而,在我的代码中,当我这样做时:

var bottleOnStage:Bottle = new Bottle();
addChild(bottleOnStage);
var newColor:uint = 0x00ff00;
var newColorTransform:ColorTransform = new ColorTransform();
newColorTransform.color = newColor;
bottleOnStage.Glass.transform.colorTransform = newColorTransform;

我收到此错误:

TypeError: Error #1010: A term is undefined and has no properties. at MethodInfo-1()

我访问 Glass 属性 是不是错了?是因为我还没有创建 Glass 实例吗?我对对象中的对象在 Flash 中的工作方式感到困惑。

编辑

var cap:Cap;
var glass:Glass;

以上是我的 Bottle.as 文件中的内容。在我的 Main.as 文件中我有:

var bottleOnStage:Bottle = new Bottle();
bottleOnStage.cap = new Cap();
bottleOnStage.glass = new Glass();
addChild(bottleOnStage);
var newColor:uint = 0x00ff00;
var newColorTransform:ColorTransform = new ColorTransform();
newColorTransform.color = newColor;
bottleOnStage.glass.transform.colorTransform = newColorTransform;

当我 运行 这段代码时,瓶子的 "glass" 部分没有发生任何变化。为什么是这样?我知道是这条线;我已经跟踪并调试了所有其他行,并且我正在跟踪的颜色是正确的,等等。当我使用 addChild 添加 "cap" 和 "bottle" 到 "bottleOnStage" 时,我得到了一个副本这两个符号,所以这显然不是办法。基本上,我如何在舞台上修改"cap"和"glass"?

您似乎混淆了 Classes 与实例。实例名称不能与 Class 名称(在同一范围内)同名。

Glass 是你的 class。如果你的瓶子 class 中有名称为 "Glass" 的变量,你需要重命名它,这样它就不会与你的 class 名称 Glass.[=17 混淆=]

bottleOnStage.glassInstanceName.transform.colorTransform = newColorTransform;

作为提示,为避免这种情况,最佳做法是始终让您的实例名称以小写字母开头,并始终让您的 Class 名称以大写字母开头。 (这也有助于在大多数编码应用程序以及 Stack Overflow 中突出显示代码 - 请注意大写项目是如何突出显示的?)

就您的错误而言,您的变量中可能还没有实际的 object。

正在执行以下操作:

var myGlass:Glass;

实际上并没有生成object(值为空),它只是为一个定义了一个占位符。您需要使用 new 关键字实例化才能创建实际的 object.

var myGlass:Glass = new Glass(); 

现在您将在该变量中有一个 object。


编辑

为了解决您的编辑问题,听起来您可能想要这样:

package {
    public class Bottle extends Sprite {
        public var cap:Cap;
        public var glass:Glass;

        //this is a constructor function (same name as the class), it gets run when you instantiate with the new keyword.  so calling `new Bottle()` will run this method:
        public function Bottle():void {
            cap = new Cap();
            glass = new Glass();

            addChild(cap); //you want these to be children of this bottle, not Main
            addChild(glass);
        }
    }
}

这使所有东西都密封起来,并添加瓶盖和玻璃作为瓶子的 children。所以bottle是child的main,cap和glass是children或bottle。

瓶子中玻璃属性的名称是什么?

如果你有例如:

 public class Bottle {

    public var glass : Glass;

}

您可以通过以下方式访问玻璃:

var bottle : Bottle = new Bottle();
bottle.glass = new Glass();

玻璃是class。 bottle.glass 是 class 瓶子的属性 "glass"。

希望对您有所帮助。