宜昌本地软件开发与弱电工程服务商
项目咨询 · 快速响应
您当前的位置: > 博客2 > AS2与AS3技术

[AS3]as3与return语句跳出方法

2016-10-13 00:16:48 点击量:9 标签: 收藏本文

如何跳出一个方法?
在方法内最后一条语句执行后,该方法会自动结束。用return语句可以提前跳出结束该方法。
return语句跳出当前的方法且ActionScript编译程序会继续执行方法中最初的代码。方法中在return语句后面的任何语句都被忽略。
private function sampleFunction ( ):void {
return;
trace("Never called");
}

// Called from within another method:
sampleFunction( );
// Execution continues here after returning from the sampleFuction( ) invocation
上面的例子中,return语句结束了方法中的任何动作,因此这不是一种有用的方法。更普遍的,你可以用return语句在特殊的条件下跳出一个方法。这是一个如果密码错误跳出该方法的例子:
private function checkPassword (password:String):void {

// If password is not "SimonSays", exit the function.
if (password != "SimonSays") {
return;
}

// Otherwise, perform the rest of the actions.
showForm ("TreasureMap");
}

// This method call uses the wrong password, so the
// function exits.
checkPassword("MotherMayI");

// This method call uses the correct password, so the function
// shows the TreasureMap form.
checkPassword("SimonSays");
在上面的例子中,你可能注意到了这个方法被声明为void,然而在含有return语句的方法中没有的得到编译错误。当return语句用来简单的跳出方法时,在声明为void的方法中也是有效的。
然而,如果你要用这种方式return一个值的话,就会出现编译错误。
private function sampleMethod ( ):void {
return "some value"; // This causes the compiler to generate an error.
}
注意:在ActionScript2.0中是Void,在ActionScript3.0中它变成了小写void。

ABOUT US
宜昌农人网络科技有限公司

我们是一家提供综合软件外包与弱电工程服务的技术公司。

业务涵盖定制软件、管理系统、网站、小程序、APP、系统集成、网络布线、监控安防、门禁、机房建设及长期技术维护。

公司地址:湖北省宜昌市伍家岗区东站二路6号三峡(宜昌)大数据产业园海洋馆二楼A203室