Actionscript 3 退出函数后在全局范围内使用局部变量
我了解AS3的工作方式如下Actionscript 3 退出函数后在全局范围内使用局部变量,actionscript-3,apache-flex,flash-builder,Actionscript 3,Apache Flex,Flash Builder,我了解AS3的工作方式如下 var str1:String = "Global"; function scopeTest () { var str1:String = "Local"; trace(str1); // Local } scopeTest(); trace(str1); // Global 我怎样才能让它像这样工作?看到最后一行了吗 var str1:String = "Global"; function scopeTest () {
var str1:String = "Global";
function scopeTest ()
{
var str1:String = "Local";
trace(str1); // Local
}
scopeTest();
trace(str1); // Global
我怎样才能让它像这样工作?看到最后一行了吗
var str1:String = "Global";
function scopeTest ()
{
var str1:String = "Local";
trace(str1); // Local
}
scopeTest();
trace(str1); // Local
还是用这个
var str1:String = "Global";
function scopeTest ()
{
//use "this" keyword
this.str1 = "Local";
var str1:String = "Local";
trace(str1); // Local
}
scopeTest();
trace(str1); // Local
完整示例代码:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
creationComplete="init(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
protected function init(event:FlexEvent):void
{
scopeTest();
trace(str1); // Local
}
public var str1:String = "Global";
public function scopeTest():void
{
//use "this" keyword
this.str1 = "Local";
var str1:String = "Local";
trace(str1); // Local
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
</s:Application>
更改变量名称以避免冲突。Var名称很便宜。为什么要重用它们,尤其是在它们可能导致冲突的情况下?当您在新范围中使用var
关键字时,它会将新属性附加到该范围。只需在函数中省略str1
的声明:
function scopeText():void
{
str1 = 'Local';
}
这将查找现有属性的外部范围
str1
具有此属性的属性不起作用。第一个检查完整的代码。它起作用了。您可以像在原始帖子中一样省略public和return类型,编译器将发出提示,但它仍然可以工作。@user3699728如果是这种情况,那么您的示例代码可能与您实际拥有的不匹配。我刚刚了解了AS3中变量的作用域在编写“variable scope”时有大量的在线源代码。你们可以在提出这个问题之前至少读一点书,这个问题非常基本,而且被回答了很多次。。
function scopeText():void
{
str1 = 'Local';
}