我试图创建一个可重用的函数,可以将全局变量作为参数,然后更改该变量,以便其他函数可以使用它。但是我的理解是,为函数创建的参数仅限于该函数,因此我无法更改全局变量。
该函数需要能够将不同的vars作为参数(参见第9和14行)。如何在第1行更改myVar以便其他功能可以读取它?
感谢您的投入!
1. var myVar1:Boolean;
2. var myVar2:Boolean;
3.
4. myMc1.addEventListener(MouseEvent.CLICK, onMC1Clicked);
5. myMc2.addEventListener(MouseEvent.CLICK, onMC2Clicked);
6.
7. function onMC1Clicked(evt:MouseEvent):void
8. {
9. toggleState(myMc1, myVar1, myFunction);
10. }
11.
12. function onMC2Clicked(evt:MouseEvent):void
13. {
14. toggleState(myMc2, myVar2, myFunction);
15. }
16.
17. function toggleState(mc:MovieClip, _switch:Boolean, funct:Function):void
18. {
19. switch (_switch)
20. {
21. case false:
22. _switch = true;
23. mc.gfx1.visible = true;
24. mc.gfx2.visible = false;
25. break;
26.
27. case true:
28. _switch = false;
29. mc.gfx1.visible = false;
30. mc.gfx2.visible = true;
31. break;
32. }
33. funct();
34. }
35.
36. fuction myFunction():void
37. {
38. trace('fired');
39. }
答案 0 :(得分:0)
正如我在评论中所述, 在AS3中,属于基本数据类型(包括Boolean,Number,int,uint和String)的对象的行为就像它们是按值传递,而不是通过值传递。您需要将基元包装为非基本类型,例如对象,然后通过引用传递。 http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f56.html
而不是toggleState(myMc1, myVar1, myFunction);
你会做toggleState(myMc1, {bool:myVar1}, myFunction);
你的功能看起来像这样:
function toggleState(mc:MovieClip, myBoolObject:Object, funct:Function):void
{
var _switch:Boolean = myBoolObject.bool;
switch (_switch)
{
//etc...
}
}
但是...
由于你的MC的行为方式相同,我建议使用这种方法整合一些代码:
//MovieClips are dynamic classes, meaning you can dynamically add properties to them
myMc1._toggled = false;
myMc2._toggled = false;
//You can share the same event handler for both buttons
myMc1.addEventListener(MouseEvent.CLICK, onMCClicked);
myMc2.addEventListener(MouseEvent.CLICK, onMCClicked);
function onMC1Clicked(evt:MouseEvent):void
{
//Get the clicked button
var mc:MovieClip = evt.currentTarget as MovieClip;
toggleState(mc, myFunction);
}
function toggleState(mc:MovieClip, funct:Function):void
{
//change the button state
mc._toggled = !mc._toggled;
mc.gfx1.visible = !mc._toggled;
mc.gfx2.visible = mc._toggled;
funct();
}
fuction myFunction():void
{
trace('fired');
}
答案 1 :(得分:0)
您可以做的是使函数获取对象和属性名称(字符串),然后使用array access ([]
)语法更改对象的属性。例如:
function toggle(object:Object, property:String):void {
object[property] = !object[property];
}
var object:Object = { checked: true }
trace(object.checked); // true
toggle(object, "checked");
trace(object.checked); // false