问题
I'm trying to optimize and existing piece of WebGl JavaScript code, and the bottleneck of the code is at an if statement with return at the end however, the return statement doesn't seem to return anything.
function render() {
if (object.loading) return; // there is no value after return
// Loading is a boolean indicating if information is still being parsed from a file or not
}
This is the first time I'm seeing code that has a return statement without a succeeding variable specified to be returned after it.
Without the return the program fails so its definitely important it is there.
Does JavaScript have a special situation in which return can be used without specifying what is being returned after it?
回答1:
If you use return with no value after it, it returns the value undefined. This is used to stop a function without returning a value. A function will also return undefined if it ends without a return statement.
http://jsfiddle.net/Q9UJg/1/
回答2:
It is used in this case like a get out clause, simple breaking out of the execution of the function prematurely because a required condition has not been met. Is that the entire function or is there more after the comment?
回答3:
There is nothing wrong with not returning a value. In your example it just means that the function finishes executing on that line: code after the return is not executed if that conditional is true.
来源:https://stackoverflow.com/questions/6735336/return-function-in-javascript-and-how-it-works