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.
Dir.prototype.refs[label]->this.refs[label]. If you want to interact with the instance, it's justthis. You're not interacting with the prototype or statically with the class.refsto remember all previous instances with a dictionary of labels