-2
class Data {

  #some_private_var

  constructor(private_val, regular_val) {
    this.regular_var = regular_val
    this.#some_private_var = private_val
  }
}

For example, if I use Axios to make an API request with an instance of the above class as the body of the request, what gets send over to the server?

Will #some_private_var get sent over?

What if a getter method is defined like so:

  get some_private_var() {
    return this.#some_private_var
  }
  • Axios won't be able to access `.#some_private_var`, it's private! – Bergi Aug 04 '22 at 02:39
  • So you are saying that only `regular_var` will be sent over? – Bear Bile Farming is Torture Aug 04 '22 at 02:40
  • 4
    Instead of asking here, why not just test it and see what gets sent? – Phil Aug 04 '22 at 02:40
  • 1
    Best way to know whether something works or not.... the best policy (in most cases) is to try yourself. – itachi Aug 04 '22 at 02:43
  • 1
    According to the documentation, "*By default, axios serializes JavaScript objects to `JSON`.*" So unless you set a specific content-type, [`JSON.stringify` happens](https://stackoverflow.com/questions/69848044/private-fields-in-javascript-dont-show-up-in-json-stringify). – Bergi Aug 04 '22 at 02:43

1 Answers1

1

Axios by default serialises JavaScript objects via JSON.stringify().

You can easily see what the result of that would be. The behaviour of which is defined here...

All the other Object instances [...] will have only their enumerable properties serialized.

class Data {

  #some_private_var

  constructor(private_val, regular_val) {
    this.regular_var = regular_val;
    this.#some_private_var = private_val;
  }
}

console.log(JSON.stringify(new Data("private", "regular")));

Private properties and methods are not enumerable properties.

If you want to expose members that would otherwise be hidden, create a toJSON() method

If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized

class Data {

  #some_private_var

  constructor(private_val, regular_val) {
    this.regular_var = regular_val;
    this.#some_private_var = private_val;
  }
  
  toJSON() {
    return {
      ...this,
      some_private_var: this.#some_private_var
    };
  }
}

console.log(JSON.stringify(new Data("private", "regular")));
Phil
  • 157,677
  • 23
  • 242
  • 245