우리는 두 개의 숫자를 더하는 것과 같은 간단한 작업을 수행하는 함수를 작성해야 합니다. 다른 함수에서 또는 전역적으로 해당 함수 내부에 선언된 변수에 액세스할 수 있는 방법을 보여줘야 합니다.
예
다음은 코드입니다 -
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