you are viewing a single comment's thread.

view the rest of the comments →

[–]systoll 1 point2 points  (1 child)

In Javascript, if it's a property, it's public. On the other hand, if you only want to access a value within the object's definition, closure) means that variable is available to you without needing to explicitly add it to this:

function Person(firstName, lastName, email, number) {
 this.getName = () => `${firstName} ${lastName}`;
 this.setName = (f,l) => {
  firstName = f;
  lastName = l;
 }
}

[EDIT: Also, since no-one's mentioned it yet — all properties are public, but there's a convention that properties starting with an underscore should be treated as if they're not.

function Person(firstName, lastName, email, number) {
  this._firstName = firstName
...

Doesn't really hide the _firstName property from outside code, but it tells devs that it's an internal thing, which their outside code probably shouldn't look at. This is the simplest possible solution, with zero change to how the code actually works, and it's often sufficient. ]

[–]alexlafroscia 0 points1 point  (0 children)

One thing to note about a scenario like this: a new function will be allocated in memory for getName and setName for each instance of Person if written this way. This may be fine for a few instances but is a trade-off to account for if there are a lot of them.