How to pass variables into inline functions in Action Script 2

时光毁灭记忆、已成空白 提交于 2019-12-02 05:18:46

问题


I have the following function, but I can't seem to get the myVar variable into the inline function. What am I doing wrong here? What I would like to have happen is when I click on myMc, it should print myVar to the console ("hello computer").

function doSomething():Void
{   
    myVar = "hello computer";

    myMc.onRelease = function(){
        trace(myVar); //prints as "undefined"
    }
}

ps. - I cannot declare myVar as a global or static variable because in the real code, I'm parsing XML and the myVar is constantly changing.


回答1:


This is a scope issue - when you apply an onRelease function like this in as2, the scope of the function is the MovieClip you apply the function to, not the calling function.

Because you are using AS2 and MovieClip is dynamic, you can assign the variable to the MC directly:

function doSomething():Void
{   
    myMc.myVar = "hello computer";

    myMc.onRelease = function(){
        trace(this.myVar);
    }
}



回答2:


Try declaring myVar with the var keyword:

var myVar = "hello computer";


来源:https://stackoverflow.com/questions/1713813/how-to-pass-variables-into-inline-functions-in-action-script-2

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