如何使用JavaScript从另一个函数访问在函数中声明的变量?

我们必须编写一个函数来完成一些简单的任务,例如将两个数字相加。我们需要演示如何访问其他函数或全局函数中声明的变量的方法。

示例

以下是代码-

const num = 5;
const addRandomToNumber = function(num){
   //之间的随机数
   const random = Math.floor(Math.random() * 10);
   //将随机数分配给该函数的对象
   //这样我们可以在外部访问它
   this.random = random;
   this.res = num + random;
};
const addRandomInstance = new addRandomToNumber(num);
const scopedRandom = addRandomInstance.random;
const result = addRandomInstance.res;
//必须等于num的原始值,即5-
console.log(result - scopedRandom);

输出结果

以下是控制台中的输出-

5