首页 > 解决方案 > 对象中的变量范围

问题描述

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?

标签: classobjectscopethis

解决方案


的值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


推荐阅读