try finally return

看到如下代码:
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#pseudo-code-of-apply-

function $apply(expr) {
 try {
   return $eval(expr);
 } catch (e) {
   $exceptionHandler(e);
 } finally {
   $root.$digest();
 }
}

很好奇,按说 return 语句执行了,后续的代码就不再执行了,可是按照 try...catch...finally 语句的逻辑,finally 语句又是必须执行的,那么如果是下面的情况呢:

function test() {
 try { return 1; }
 catch (e) {}
 finally { return 2; }
}

执行函数后返回什么呢?
结果是:2

Javascript: try/catch return statement - stackoverflow
http://stackoverflow.com/questions/3837994/javascript-try-catch-return-statement

对第二个回答搬出来的资料更感兴趣:

According to ECMA-262 (5ed, December 2009), in pp. 96:

The production TryStatement : try Block Finally is evaluated as follows:
1. Let B be the result of evaluating Block.
2. Let F be the result of evaluating Finally.
3. If F.type is normal, return B.
4. Return F.

And from pp. 36:

The Completion type is used to explain the behaviour of statements (break, continue, return and throw)
that perform nonlocal transfers of control. Values of the Completion type are triples of the form (type, value,
target), where type is one of normal, break, continue, return, or throw, value is any ECMAScript language
value or empty, and target is any ECMAScript identifier or empty.

也就是说,只在 finally 语句的执行结果不是 return 类型时,才会使用 try 语句块的执行结果作为返回值。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容