Demo cách truy cập biến cục bộ của hàm từ bên ngoài: gán vào this của constructor function.
Giải pháp
Mã triển khai:
const num = 5;
const addRandomToNumber = function(num) {
const random = Math.floor(Math.random() * 10);
this.random = random; // Gán vào instance
this.res = num + random; // Gán kết quả
};
const instance = new addRandomToNumber(num);
const scopedRandom = instance.random;
const result = instance.res;
// Kiểm tra: result - random = num ban đầu (5)
console.log(result - scopedRandom);
Kết quả
Đầu ra trong console:
5
Giải thích: Dùng new tạo instance, this tham chiếu đến instance đó. Có thể truy cập instance.random và instance.res từ bên ngoài.
Cách hiện đại: Dùng closure hoặc return object {random, res} thay vì constructor function.