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

js毁三观系列 #3

Open
LeeeeeeM opened this issue Dec 4, 2018 · 3 comments
Open

js毁三观系列 #3

LeeeeeeM opened this issue Dec 4, 2018 · 3 comments

Comments

@LeeeeeeM
Copy link
Owner

LeeeeeeM commented Dec 4, 2018

原本以为函数体里面执行return之后,后面的代码都是unreachable的,没想到啊没想到,如果被try块包裹,finally块内的代码还是会执行。

function a() {
	try {
		return console.log(2)
	} finally {
		console.log(3)
	}
}
@LeeeeeeM
Copy link
Owner Author

LeeeeeeM commented Dec 4, 2018

继续深究。

function a() {
	try {
		return 2
	} finally {
		console.log(3)
	}
	console.log(4)
}
var b = a()
console.log(b)

输出 3 2

在此我们不得不佩服try/finally 包裹的代码块,居然优先级比return还要高。
看来js中的捕获异常相关的代码更接近底层。

@LeeeeeeM
Copy link
Owner Author

LeeeeeeM commented Dec 4, 2018

继续

function a() {
	try {
		return xxx()
	} finally {
		console.log(3)
	}
	console.log(4)
}
var b = a()
console.log(b)

先执行finally之后抛出异常。

@LeeeeeeM
Copy link
Owner Author

LeeeeeeM commented Dec 4, 2018

function a() {
	try {
		return xxx()
	} catch(e) {
		console.log(2)
		return 5
	}finally {
		console.log(3)
	}
	console.log(4)
}
var b = a()
console.log(b)

输出2 3 5

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

No branches or pull requests

1 participant