Home > Web Front-end > JS Tutorial > Use of function nesting in JavaScript_Basic knowledge

Use of function nesting in JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 15:56:48
Original
1498 people have browsed it

Before JavaScript 1.2, function definitions were only allowed in top-level global code, but JavaScript 1.2 can nest function definitions in other functions.

Still existing function definitions can be looped or restricted within conditions without appearing. These restrictions on function definitions apply only to function declarations and function statements.

Function literals (another feature introduced in JavaScript 1.2) may appear in any JavaScript expression, which means they can appear inside if else statements.
Example:

Here are examples of our two nested functions. This can be a little confusing, but it works perfectly:

<script type="text/javascript">
<!--
function hypotenuse(a, b) {
  function square(x) { return x*x; }
  
  return Math.sqrt(square(a) + square(b));
}
//-->
</script>

Copy after login

Note: Here, we are using the sqrt function from the math class.

Now, this function can be called in the usual way as follows:

<script type="text/javascript">
<!--
hypotenuse(1, 2); // This will produce 2.2360
//-->
</script>

Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template