1

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;
  }
}
2
  • You've basically implemented a singleton. Commented Aug 31, 2015 at 19:31
  • Try what happens with two instances. Commented Aug 31, 2015 at 19:52

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.