在对象方法中设置超时后访问 "this" 属性时出错
Error with accessing "this" properties after settimeout in object method
"Unable to get property 'style' of undefined or null reference" 定义的变量。
我正在尝试制作一个加密设备来测试我的技能。当您按下键盘上的某个键时,我的 "keys" 会亮起,所以我按下 "A",然后 "G" 会亮起。
我使用了调试器,所有变量都很好,但是当代码设置 属性 时,else 语句上的所有内容都会中断,当超时结束时,留下浅黄色。
我尝试重命名函数,因为 "key" 是关键字,我尝试指定 "on"(这消除了错误但没有任何反应),我尝试将变量 x 切换为 this.x。 (抱歉格式太糟糕了)
<!DOCTYPE HTML>
<html>
<head>
<script>
function key(specId, on = false) {
this.elemId = specId;
this.state = on;
this.docId = document.getElementById(`${this.elemId}`);
this.blink = function() {
if(!this.state) {
this.docId.style.backgroundColor = "yellow";
this.state = true;
var x = setTimeout(this.blink, 1000);
}
else {
this.docId.style.backgroundColor = "black";
this.state = false;
}
}
}
var a = new key("keyA");
a.blink();
</script>
<style>
.key {
background-color:black;
border:1px solid #000000;
color:white;
height:36px; /* twice the size of the font */
width:36px;
border-radius:50%;
text-align:center;
}
</style>
</head>
<body>
<div id="keyA" class="key">A</div>
</body></html>
应该发生的是当 window 加载时,屏幕上的灯 "A" 变黄一秒钟,然后变回黑色。但是,目前灯变成黄色,一秒钟后(超时)我得到上面的错误。
调用 setTimeout 中的 blink 函数时需要绑定 'this' 上下文,如下所示:
var x = setTimeout(this.blink.bind(this), 1000);
我试过了。工作正常。希望对您有所帮助:)
"Unable to get property 'style' of undefined or null reference" 定义的变量。
我正在尝试制作一个加密设备来测试我的技能。当您按下键盘上的某个键时,我的 "keys" 会亮起,所以我按下 "A",然后 "G" 会亮起。
我使用了调试器,所有变量都很好,但是当代码设置 属性 时,else 语句上的所有内容都会中断,当超时结束时,留下浅黄色。
我尝试重命名函数,因为 "key" 是关键字,我尝试指定 "on"(这消除了错误但没有任何反应),我尝试将变量 x 切换为 this.x。 (抱歉格式太糟糕了)
<!DOCTYPE HTML>
<html>
<head>
<script>
function key(specId, on = false) {
this.elemId = specId;
this.state = on;
this.docId = document.getElementById(`${this.elemId}`);
this.blink = function() {
if(!this.state) {
this.docId.style.backgroundColor = "yellow";
this.state = true;
var x = setTimeout(this.blink, 1000);
}
else {
this.docId.style.backgroundColor = "black";
this.state = false;
}
}
}
var a = new key("keyA");
a.blink();
</script>
<style>
.key {
background-color:black;
border:1px solid #000000;
color:white;
height:36px; /* twice the size of the font */
width:36px;
border-radius:50%;
text-align:center;
}
</style>
</head>
<body>
<div id="keyA" class="key">A</div>
</body></html>
应该发生的是当 window 加载时,屏幕上的灯 "A" 变黄一秒钟,然后变回黑色。但是,目前灯变成黄色,一秒钟后(超时)我得到上面的错误。
调用 setTimeout 中的 blink 函数时需要绑定 'this' 上下文,如下所示:
var x = setTimeout(this.blink.bind(this), 1000);
我试过了。工作正常。希望对您有所帮助:)