【问题标题】:Variable scope in Object对象中的变量范围
【发布时间】:2020-12-21 20:14:35
【问题描述】:
class Hangman{
    constructor(lives){
        this.hintChoice=5;
        this.lives=lives;
        this.newGame();
        
    }
    newQuestion(){
        this.hintChoice=10;//PROBLEM LINE 
    }
    
    displayClue(){
        clueDiv.innerText='Clue -'+' '+ this.hintChoice; 
    }
}

调用newQuestion()时,为什么this.hintChoice的值没有全局变为10?

【问题讨论】:

    标签: class object scope this


    【解决方案1】:

    this 的值是由很多因素决定的。在您的示例中,您有一个类,而在其中调用函数的唯一方法是创建该类的实例。

    创建类实例并调用的正确方法如下。如果您想了解更多信息,请在此处阅读我的博客:https://dbwriteups.wordpress.com/2017/04/08/what-does-that-this-in-javascript-mean/

    class Counter {
        constructor(count) {
            this.count = count;
        }
        increment() {
            this.count++;
        }
        getCount() {
            return this.count;
        }
    
        setCount(value) {
            this.count = value;
        }
    }
    
    let counter = new Counter(5); // Instance of class created.
    console.log(counter.getCount()); // Prints 5
    counter.increment(); // Increments count to 6
    console.log(counter.getCount()); // Prints 6
    counter.setCount(10); // Sets count to 10
    counter.increment();  // Increments count to 11
    console.log(counter.getCount()); // Prints 11

    【讨论】:

    • 假设我创建了一个 Hangman 对象,当事件监听器调用 newQuestion() 时 this.hintChoice 的值是否应该全局更改?
    • 是的,当然。正如我所说,this 的值是根据调用上下文分配的。如果您通过我的答案中的博客链接,您将能够自己弄清楚。
    猜你喜欢
    • 1970-01-01
    • 2012-01-21
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多