1

Why am I not able to access variables inside the constructor?

class Dir {
  refs = {};

  constructor(dir, label, reverse, clockwise) {
    this.dir = dir;

    // error: refs is not defined
    Dir.prototype.refs[label] = { ref: this, reverse, clockwise };
    // this wont work either
    Dir.refs[label] = { ref: this, reverse, clockwise };
  }
}

// test
const dirU = new Dir([0, -1], 'U', 'D', 'R');

refs is accessible outside the constuctor:

class Dir {
  refs = {};
  constructor(dir, label, reverse, clockwise) {
    this.dir = dir;
  }
}
const dirU = new Dir([0, -1], 'U', 'D', 'R');
console.log(dirU.refs);
// will print '{}'

This will solve it, but it is much less convient:

class Dir {
  constructor(dir, label, reverse, clockwise) {
    this.dir = dir;
    if (!(label in Dir.prototype)) Dir.prototype.refs = {};
    Dir.prototype.refs[label] = { ref: this, reverse, clockwise };
  }
}

How can I access class variable inside the constructor? Is this even possible in javascript?

clarification:i want refs to remember all previous instances with a dictionary of labels. I want the Dir class to hold a dictionary of all of his instances. in python this is how you would write it, but in javascript it doesn't work.

2
  • 2
    Dir.prototype.refs[label] -> this.refs[label]. If you want to interact with the instance, it's just this. You're not interacting with the prototype or statically with the class. Commented May 18, 2021 at 10:31
  • no, i want refs to remember all previous instances with a dictionary of labels Commented May 18, 2021 at 10:33

1 Answer 1

3

Make refs static. Then use Dir.refs. That is:

class Dir {
  static refs = {};

  constructor(dir, label, reverse, clockwise) {
    this.dir = dir;
    Dir.refs[label] = { ref: this, reverse, clockwise };
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

great! thanks! will accept it in 3 minutes.
@EliavLouski ... how about the concern you were raising in your Q. of not exposing the references into public? ... "... refs is accessible outside the constructor ...". This above provided approach does not prevent it. The only approach which does fully cover this requirement was to use additional encapsulation.
@PeterSeliger actually, I want it to be accessible publicly

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.