Can not access private field through public get via proxy

Viewed 503

When getting Data from a VueX Module via Getter the Object is wrapped with a Proxy that throws following error:

TypeError: attempted to get private field on non-instance

when trying to read a private property with a public getter.

class Example {
  #privateField;

  get privateField() {
    return this.#privateField;
  }
}
computed(){
  getInfoForSpecificItem() {
    const arrayOfInstantiatedExamples = this.$store.getters['getArrayOfInstantiatedExamples'];
    for (let i = 0; i < arrayOfInstantiatedExamples.length; i += 1) {
      // trying to access it in this condition throws the error since the Object
      // has been wrapped with a Proxy coming from Vue (I guess)
      if (arrayOfInstantiatedExamples[i].privateField === 'something') {
        // does something
      }
    }
  }
}

Why am I not able to read the property, and how can I create an instance from the proxy target. logging the Proxy Object reveals, that the target has all information, yet trying to read it via getter doesn't work.

Are there any other options than making the fields public?

1 Answers

You are defining a class not a function. So remove the parentheses().

class Example {

You cannot define variable with #. Only $ and _ are allowed to use in a variable. So replace # with $ like this $privateField;

Classes are blueprints, not a valid object. First make an object from this class.

const proxyWrappedExample = new Example;

After you log this then you can avoid the error but it logs undefined.

Your code should look like

class Example {
  $privateField = 'something';

  get privateField() {
    return this.$privateField;
  }
}

const proxyWrappedExample = new Example;

// I receive the Object (which has been instantiated earlier) wrapped in a proxy Object. 
// Trying to access the property throws the error.
// e.g.:

console.log(proxyWrappedExample.privateField); // 'something'

$privateField without any value will look like following.

class Example {
  $privateField;

  get privateField() {
    return this.$privateField;
  }
}

const proxyWrappedExample = new Example;

// I receive the Object (which has been instantiated earlier) wrapped in a proxy Object. 
// Trying to access the property throws the error.
// e.g.:

console.log(proxyWrappedExample.privateField); // 'undefined'
Related