วิธีทำ
ใช้ return keyword สำหรับ outer function call
ตัวอย่างโค้ด
var substractMethod = function () {
var firstValue = 1000, thirdValue = 200;
var divideMethod = function () {
var secondValue = 500;
console.log("The result of divideMethod()=" + (firstValue/secondValue));
return (firstValue - secondValue);
};
return divideMethod;
}
var result = subtractMethod();
console.log("The result of substractMethod()=" + result());
วิธีรัน
node fileName.js
ชื่อไฟล์ demo198.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo198.js The result of divideMethod()=2 The result of subtractMethod()=500
คำอธิบาย
substractMethod return function divideMethod (closure)
เรียก substractMethod() ได้ function divideMethod กลับมา เก็บใน result
เรียก result() จะ execute divideMethod ได้ 500 (1000-500)
divideMethod เข้าถึง firstValue จาก outer scope ได้ (closure)