Ссылка на локальную переменную класса внутри метода, который находится в объекте, который находится в том же классе - PullRequest
0 голосов
/ 10 октября 2018

Вот пример кода.

class TestClass {
    constructor() {
        let question = "How could I refer this variable inside of the nested object?"
    }
}

TestClass.prototype.category = {
    validate : function () {
        return true;
    }
    , read : function () {
        // this in here is not TestClass. How could I refer TestClass Instance(caller) in strict mode ?
        console.log('Inside of TestClass.prototype.category.read', this);
        if(this.validate) {
            console.log('I would like to refer TestClass.question', this.question);
        }
    }
}

TestClass.prototype.readCategory = function () {
    this.category.read();
}

Затем я делаю что-то вроде ниже в консоли редактора Chrome.

var test = new TestClass();
test.readCategory();

// result is like below
I would like to refer TestClass.question undefined

Насколько я знаю, я предполагаю, что

  1. При использовании ключевого слова new я сгенерирую экземпляр, содержащий переменную question и методы, которые я вставил в prototype
  2. Затем он выполнит readCategory(), онвызывает instance.category.read, но в этот момент ключевое слово this будет указывать instance.read объект, а не экземпляр TestClass.Так что this.question будет значением undefined.
  3. Итак, вот вопрос, как я могу получить доступ к переменной вызывающего (или экземпляра класса)?

Я обнаружил, что когда мы используем class, невозможно использовать this.caller. (Автоматически применяется строгий режим).

Как мне получить доступ к переменной класса в этой ситуации?Thanx.

1 Ответ

0 голосов
/ 10 октября 2018

Вы не можете, ваша переменная 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();
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...