如何使用 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP