Why does a return in `finally` override `try`?

后端 未结 10 2004
栀梦
栀梦 2020-12-12 15:22

How does a return statement inside a try/catch block work?

function example() {
    try {
        return true;
    }
    finally {
        return false;
             


        
10条回答
  •  粉色の甜心
    2020-12-12 16:09

    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.

    It's clear that return false would set completion type of finally as return, which cause try ... finally to do 4. Return F.

提交回复
热议问题