actionscript 3 - AS3 create a variable in root from within a function -
i have big swf right bit of coding already. vars created in root, have problem.
i want reload flash swf (reset), , that, need create function destroys vars , 1 creates them. @ moment, have javascript function reloads page, isnt solution.
the problem when create var inside function, doesn't created in "movieclip(root)", , instead related function, rendering swf unable work.
is there way create vars in movieclip(root) within function? or there alternative i'm trying do?
edit: added example code.
function setvar():void{ var test:string= new string("foobar"); } setvar(); trace(test);
...and output is:
scene 1, layer 'layer 1', frame 1, line 7 1120: access of undefined property test.
which normal, because "var test" not global, lost when function ended. want make function "setvar()" adds vars root, or global.
you need read on how scope works.
basically:
- an object declared within object (be class, function, object, or loop), available within specific object or loop iteration.
- object scope inherited children, not parents. function within class has access object declared within class, class not have access object declared within function
- a parent (or other object) can access objects declared within child classes, if
public
object
so looking @ basic rules (they very, basic. if starting out, urge proper research object scope in oop. basis of in dozens of languages), declaring object in function , trying access outside function. breaks rule #1 above.
instead, try this:
var test:string; function setvar():void{ this.test = 'foorbar'; } trace(test); //output: null (undeclared) setvar(); trace(this.test); // output: foobar
looking @ this, did 2 things:
- i moved declaration of
test
global space, meaning object in object have access it - i renamed
setvar
setvar
. has nothing question, in as3, standard naming conventions dictate use lowercasecamelcase objects (including functions), uppercasecamelcase class names, , lowercasename package names. again, unrelated learn.
now, ideally, want setvar
function differently. allow better abstraction (basically making code generic reusable possible), want return value function rather manually set variable in function.
var test:string; var anothertest:string; function setvar():string { return 'foorbar'; } this.text = setvar(); this.anothertest = setvar(); trace(this.test); // output: foobar trace(this.anothertest); // output: foobar
so allows use function string
variable imaginable. obviously, not useful here since doesn't logic. sure can see how expanded more code make more dynamic , more useful
edit: afterthought, used this
keyword. in as3 (and few other languages), this
refers scope of current class (or current frame, in case of timeline frame coding). this.test
refers variable test
declared in scope of frame or class.
Comments
Post a Comment