class - 对象中的变量范围
问题描述
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?
解决方案
的值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
推荐阅读
- python - 在 or-tools python 中为调度问题添加软约束
- java - 如何包含依赖关系的 Javadoc 和源代码
- reactjs - 道具未在 NextJs 中渲染
- java - Main.java:12:错误:缺少返回语句 } ^
- spring-security - spring-security-saml2-service-provider 的“未提供 KeyInfo 生成器”
- ios - 我想我已经完成了必要的代码签名工作,但在 Ionic 中构建仍然失败
- python - 缩放 GeoJSON 以查找附近的纬度和经度点
- python - 支持命令 discord.py
- java - Netflix zuul:通过 HTTP CONNECT 调用为 squid 等出站代理服务器配置 TLS 传递
- python - 遍历页面的while循环中的StaleElementReferenceException