如何使用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
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短