Вы не можете, ваша переменная category
полностью приватна для конструктора.Как только конструктор вернется, он исчезнет.
Ваша структура довольно необычна, но если вам действительно нужно, чтобы category
был подчиненным объектом, но вы все равно хотите, чтобы он имел доступ к TestClass
экземпляру, к которому он относитсядля этого можно использовать функции стрелок, созданные в конструкторе, см. комментарии:
class TestClass {
constructor() {
// Make question a property
this.question = "How could I refer this variable inside of the nested object?"
// Make category an instance property using arrow functions
this.category = {
validate : () => {
return true;
}
, read : () => {
console.log('Inside of TestClass.prototype.category.read', this);
if(this.category.validate()) { // <=== Need to add `category.` and `()`
console.log('I would like to refer TestClass.question', this.question);
}
}
};
}
// No reason to define this outside the `class` construct, make it a method
readCategory() {
this.category.read();
}
}
Использование предложения полей класса (в настоящее время на этапе 3, поэтому вам потребуется выполнить перенос), вы также можете написать это так:
class TestClass {
// Make category an instance property using arrow functions
category = {
validate : () => {
return true;
}
, read : () => {
console.log('Inside of TestClass.prototype.category.read', this);
if(this.category.validate()) { // <=== Need to add `category.` and `()`
console.log('I would like to refer TestClass.question', this.question);
}
}
};
constructor() {
// Make question a property
this.question = "How could I refer this variable inside of the nested object?"
}
// No reason to define this outside the `class` construct, make it a method
readCategory() {
this.category.read();
}
}
Это фактически то же самое, что и в первом примере;инициализаторы полей выполняются как в конструкторе.
Если вы не хотите, чтобы question
являлось свойством экземпляра, поскольку это функции стрелок, определенные в конструкторе, вы можете оставить его как локальныйпеременная, которую они закрывают:
class TestClass {
constructor() {
let question = "How could I refer this variable inside of the nested object?"
this.category = {
validate : () => {
return true;
}
, read : () => {
console.log('Inside of TestClass.prototype.category.read', this);
if(this.category.validate()) {
console.log('I would like to refer TestClass.question', question); // <== No `this.`
}
}
};
}
readCategory() {
this.category.read();
}
}