Class property looses scope AND can't be set after setTimeout

爷,独闯天下 提交于 2020-01-07 06:57:13

问题


Here's a very simplified version of my project.

I have a class file:

class MyClass{

public var myNumberStoredInClass:Number;

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

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

}; // end class

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);

};

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.

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
};

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.

I have to use AS2 for this.

Any ideas? Many thanks.

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


回答1:


A closure should work. Your code:

 setTimeout(MyClass.DoStuffMethod, 7500);

becomes:

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

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

This should also work:

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

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

Hope this helps.



来源:https://stackoverflow.com/questions/32270228/class-property-looses-scope-and-cant-be-set-after-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!