Understanding Private Variables in JavaScript Class Constructors
This week, my class has been looking into factory functions and classes. Naturally, the topic of 'private variables' came up, and has been a source of much confusion. To me, this confusion is similar to the confusion over Closure, which I addressed i...
blog.annamcdougall.com4 min read
This really helped me understand what this "private variable" was really about. Thank you, Anna, for this wonderful explanation. just one thing:
class User { constructor(name, age, favNumber) { let superSecretNumber = Math.round((age * favNumber) / name.length); function logOutcome() { console.log(`Wow! Your secret number is ${superSecretNumber}`); } return { name, age, favNumber, logOutcome }; } } let firstUser = new User("Anna", 33, 7); console.log(firstUser.name); // logs "Anna" console.log(firstUser.superSecretNumber); // WHOMP WHOMP: 'undefined' firstUser.logOutcome(); // logs "Wow! Your secret number is 58"Isn't the constructor function ONLY for assigning arguments to variables we use inside the class? shouldn't we declare the supersecretnumber outside the constructor? and why are assigning the values outside the constructor?