Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completion 类型 #15

Open
K-Kevin opened this issue Mar 12, 2020 · 0 comments
Open

Completion 类型 #15

K-Kevin opened this issue Mar 12, 2020 · 0 comments

Comments

@K-Kevin
Copy link
Owner

K-Kevin commented Mar 12, 2020

Completion类型

在try中有return语句,finally中的内容还会执行吗?

function foo(){
  try{
    return 0;
  } catch(err) {

  } finally {
    console.log("a")
  }
}

console.log(foo());

输出:

a
0

虽然 return 执行了,但是函数并没有立即返回,又执行了 finally 里面的内容,这样的行为违背了的直觉。

如果在这个例子中,我们在 finally 中加入 return 语句,会发生什么呢?

function foo(){
  try{
    return 0;
  } catch(err) {

  } finally {
    return 1;
  }
}

console.log(foo());

输出:

1

可以看出,finally中的return 覆盖了try中的return,在一个函数中 return 两次,似乎是不太可能的。

这一机制的基础是JavaScript语句执行的完成状态:Completion Record(Completion Record用于描述异常、跳出等语句执行过程)。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant