如何使用 JavaScript 從另一個函式訪問在一個函式中宣告的變數?


我們必須編寫一個執行一些簡單任務的函式,比如加兩個數之類。我們要求演示如何在其他函式或全域性訪問在該函式中宣告的變數。

示例

以下是程式碼 −

const num = 5;
const addRandomToNumber = function(num){
   // a random number between [0, 10)
   const random = Math.floor(Math.random() * 10);
   // assigning the random to this object of function
   // so that we can access it outside
   this.random = random;
   this.res = num + random;
};
const addRandomInstance = new addRandomToNumber(num);
const scopedRandom = addRandomInstance.random;
const result = addRandomInstance.res;
// must be equal to the original value of num i.e., 5
console.log(result - scopedRandom);

輸出

以下是控制檯中的輸出 −

5

更新於: 18-Sep-2020

2000+ 瀏覽量

開啟你的 職業生涯

透過完成本課程獲取認證

入門
廣告