Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ความแตกต่างระหว่าง Closure และ Nested Functions ใน JavaScript

JavaScript Closures

ใน JavaScript ทุกฟังก์ชันทำงานแบบ Closure Closure คือฟังก์ชันที่ใช้ Scope ที่มันถูกประกาศเมื่อถูกเรียก ไม่ใช่ Scope ที่มันถูกเรียกใช้

ตัวอย่าง Closure

<!DOCTYPEhtml> <html> 
  <body> 
    <h2>JavaScriptClosures</h2> 
    <script> 
      var p = 20; 
      function a(){ 
        var p = 40; 
        b(function(){ 
          alert(p); 
        }); 
      } 
      function b(f){ 
        var p = 60; 
        f(); 
      } 
      a(); 
    </script> 
  </body> 
</html>

JavaScript Nested Functions

JavaScript 1.2 อนุญาตให้ประกาศฟังก์ชันซ้อนกันได้ แต่มีข้อจำกัด: ไม่สามารถประกาศฟังก์ชันภายใน Loop หรือ Conditional ได้ ข้อจำกัดนี้ใช้กับ Function Declaration ที่ใช้คีย์เวิร์ด function

ตัวอย่าง Nested Functions

<html> 
  <head> 
    <script> 
      function hypotenuse(a,b) { 
        function square(x){return x*x;} 
        return Math.sqrt(square(a)+square(b)); 
      } 
      function secondFunction() { 
        var result; 
        result = hypotenuse(5,4); 
        document.write(result ); 
      } 
    </script> 
  </head> 
  <body> 
    <p>Click the following button to call the function</p> 
    <form> 
      <input type="button" onclick="secondFunction()" value="Call Function"> 
    </form> 
  </body> 
</html>