简体   繁体   English

在 Javascript 中返回 function 以及它是如何工作的?

[英]Return function in Javascript and how it works?

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.我正在尝试优化和现有的 WebGl JavaScript 代码,代码的瓶颈是在最后return的 if 语句,但是,return 语句似乎没有返回任何内容。

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.这是我第一次看到有一个 return 语句的代码没有指定要在它之后返回的后续变量。

Without the return the program fails so its definitely important it is there.如果没有return ,程序就会失败,所以它在那里绝对重要。

Does JavaScript have a special situation in which return can be used without specifying what is being returned after it? JavaScript有没有特殊情况可以使用return而不指定后面要返回什么?

If you use return with no value after it, it returns the value undefined .如果你使用return之后没有值,它会返回值undefined This is used to stop a function without returning a value.这用于停止 function 而不返回值。 A function will also return undefined if it ends without a return statement.如果 function 在没有返回语句的情况下结束,它也会返回undefined

http://jsfiddle.net/Q9UJg/1/ http://jsfiddle.net/Q9UJg/1/

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.在这种情况下,它就像一个退出子句一样使用,因为没有满足所需的条件,所以过早地中断了 function 的执行。 Is that the entire function or is there more after the comment?是整个 function 还是评论后还有更多?

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.在您的示例中,这仅意味着 function 完成了在该行上的执行:如果条件为真,则不会执行返回后的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM