类属性松动范围和可能的setTimeout后不能设置范围、类属、setTimeout

2023-09-08 11:48:28 作者:蓦然回首已成空

下面是我的项目的一个非常简化的版本。

Here's a very simplified version of my project.

我有一个类文件:

class MyClass{

public var myNumberStoredInClass:Number;

// constructor
function MyClass(myNumber:Number){
    this.myNumberStoredInClass = myNumber;
};

// some method
function DoStuffMethod(){
    trace(this.myNumberStoredInClass);
};

}; // end class

我有,我可以,直到我打电话的setTimeout在类中的方法,没有任何问题与MyClass.myNumberStoredInClass访问this.myNumberStoredInClass正常的。至于文件:

I have a normal .as file from which I can access this.myNumberStoredInClass with no problems with MyClass.myNumberStoredInClass until I call setTimeout for a method in the class:

function ASFileFunction(){

    trace(MyClass.myNumberStoredInClass); // works fine

    setTimeout(MyClass.DoStuffMethod, 7500);

};

当DoStuffMethod在类文件引发myNumberStoredInClass返回未定义的痕迹。我已经使用在许多其他的功能价值的。至于文件就好了,但它失去的setTimeout之后。

When DoStuffMethod is triggered in the class file the trace of myNumberStoredInClass returns 'Undefined'. I've used the value in many other functions in the .as file just fine but after the setTimeout it's lost.

什么是真正奇怪的是,我可以改变DoStuffMethod以下和myNumberStoredInClass仍然是未定义:

What's really odd is that I can change DoStuffMethod to the following and myNumberStoredInClass is still Undefined:

function DoStuffMethod(){

// I've tried watching this in debug mode and it just won't set, remains Undefined


myNumberStoredInClass = 10; 

    trace(myNumberStoredInClass); // returns Undefined
};

我在DoStuffMethod使用this.myNumberStoredInClass尝试,但结果是一样的。我只是不能设置或检索变量!如果我在的setTimeout后立即做一个跟踪的价值是存在的,但一旦setTimeout的火灾,则该值不能设置。

I've tried using this.myNumberStoredInClass in DoStuffMethod but the result is the same. I just can't set or retrieve the variable! If I do a trace immediately after the setTimeout the value is there, but once the setTimeout fires then the value can not be set.

我要使用AS2这一点。

I have to use AS2 for this.

任何想法?非常感谢。

编辑:尝试添加的对象,setTimeout调用按照文件建议的桑特gMirian,但仍是同样的结果。

Tried adding the object to the setTimeout call as per the documentation suggested by Sant gMirian but still the same result.

推荐答案

一个封闭应该工作。您的code:

A closure should work. Your code:

 setTimeout(MyClass.DoStuffMethod, 7500);

变成了:

 setTimeout(function () { MyClass.DoStuffMethod() }, 7500);

顺便说一句,我认为的 MyClass的的是你的类的实例,而不是你的类定义。

By the way, I assume that MyClass is an instance of your class, not your class definition.

这也应该工作:

function haveStuffDone () : void {
    MyClass.DoStuffMethod();
}
setTimeout (haveStuffDone, 7500);

其中的 haveStuffDone 的是在你调用的的setTimeout 的相同的上下文中定义的函数。

where haveStuffDone is a function defined in the same context you call setTimeout from.

希望这有助于。