ReluctantProgrammer
ReluctantProgrammer

Reputation: 77

Javascript proper getters

On this page, It says that to make properties limited to being read-only, use the get keyword. However I do not see the point of adding the get lang() function that basically returns the language property. I mean, yes you'd not be able to do something like person.lang = 'whatever', but you would be able to do person.language = 'whatever'. How would I properly restrict that access using getters, not writable: false?

Upvotes: 1

Views: 57

Answers (2)

neaumusic
neaumusic

Reputation: 10474

They aren't necessarily for restricting access, though they can be, but they actually run code while accessing the variable, kinda like a syntactic equivalent of .lang() (which I'd call a thunk)

You can prevent anyone from tampering with the variable by restricting them to 'read-only' and disabling that writable property in defineProperty.

If you remove public access to the underlying property, the instance can act as an accessor or proxy to it (the class instance could have a reference to a private scope that it was generated in, for example). In that manner, you'd never be able to write a value to the accessor's field, but you could still access the otherwise privately scoped variable.


If not a factory pattern like that, I could imagine defining the getter function at a later time via some third party which holds private variables. You could also pass a third party:

  1. the instance
  2. the data store
  3. some sort of registry that can verify the instance is authenticated

This third party could connect it's getter to the otherwise private data store variable, rather than during instantiation as in a factory pattern


I believe privatization comes with additional layers, and the get/set thing is just syntactic

Upvotes: 0

user128511
user128511

Reputation:

If you want to make a field private use private class fields

class Foo {
  #language
  constructor(lang) {
    this.#language = lang;
  }
  get lang() {
    return this.#language;
  }
}

const f = new Foo('Japanese');
console.log(f.lang);
//f.#language = 'German'; // error!

note: private class fields are relatively new. you'll need to use a transpiler like babel to support old browsers.

Upvotes: 1

Related Questions