user2573542
user2573542

Reputation: 33

Javascript: "private" variables when using modules

I am exporting a class where I do not want the user to be able to access the name variable. Is there anything wrong with doing it this way from a technical stand point, not personal preference? I know it's probably not a best practice, but it seems to work.

let _name = 'bob';
export default class Person {
  getName() {
    return _name;
  }

  setName(name) {
    _name = name;
  }
}

Upvotes: 1

Views: 46

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

The problem is simple - _name resides in a closure, and all instances of Person will set and get the same _name.

var a = new Person();
a.setName('John');

var b = new Person();
b.getName(); // the result will be John

Upvotes: 2

taxicala
taxicala

Reputation: 21759

Well, as what I see, my opinion is that _name is no longer private as per the code you've provided, because you are defining a getter and a setter method, which basically turns the variable to public.

You should also definitely take a look at @OriDrori's answer since he is right about the variable scope.

Upvotes: 0

Related Questions