为什么/如何'this'关键字指的是事件对象而不是全局对象,因为我在函数中使用了'this'关键字



我做了什么:

  1. 将事件侦听器添加到类型为"="的所有div;按钮">
  2. 当用户单击我记录的任何按钮时,用户会使用"this"关键字在数组中单击

代码:

var userClickedPattern = [];
var totalNoOfButtons = document.querySelectorAll("div[type=button]").length;
for (var i = 0; i < totalNoOfButtons; i++){
document.querySelectorAll("div[type=button]")[i].addEventListener("click", userClick);
}
function userClick(){
var userChosenColour = this.id;//why is 'this' referring to event object and not global object
userClickedPattern.push(userChosenColour);
console.log(userClickedPattern);
}
body {
text-align: center;
background-color: #011F3F;
}
#level-title {
font-family: 'Press Start 2P', cursive;
font-size: 3rem;
margin:  5%;
color: #FEF2BF;
}
.container {
display: block;
width: 50%;
margin: auto;
}
.btn {
margin: 25px;
display: inline-block;
height: 200px;
width: 200px;
border: 10px solid black;
border-radius: 20%;
}
.game-over {
background-color: red;
opacity: 0.8;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.yellow {
background-color: yellow;
}
.pressed {
box-shadow: 0 0 20px white;
background-color: grey;
}
/* ANIMATION */
/* KEYFRAMES */
@keyframes btn-appearance {
0% { opacity : 1; }
100% { opacity: 0; }
}
/* animation class */
.btn-sequence{
animation-name : btn-appearance;
animation-duration: 150ms;
animation-timing-function: linear;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Simon</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
</head>
<body>
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
<div class="row">
<div type="button" id="green" class="btn green">
</div>
<div type="button" id="red" class="btn red">
</div>
</div>
<div class="row">
<div type="button" id="yellow" class="btn yellow">
</div>
<div type="button" id="blue" class="btn blue">
</div>
</div>
</div>

/*jQuery*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
/*javascript*/
<script src = "game.js" type="text/javascript">
</script>
</body>
</html>

根据W3Schools关于"this"关键字的理论:根据使用位置的不同,它有不同的值:

  1. 在一个方法中,这指的是所有者对象
  2. 单独指的是全局对象
  3. 在函数中,这指的是全局对象
  4. 在函数中,在严格模式下,这是未定义的
  5. 在事件中,这指的是接收事件的元素

真正的问题: 解释为什么"this"关键字指的是事件对象,而不是全局对象,因为我在函数userClick((中使用了"this"关键词

函数中this的值由函数的调用方式决定。

不是在调用函数,而是将其传递给addEventListener,然后浏览器正在调用它(并将正在侦听的元素指定为this值(。

addEventListener就是这样设计的。


解释为什么"this"关键字指的是事件对象,而不是全局对象,因为我在函数userClick((中使用了"this"关键词

假设您的报价"在函数中,这指的是全局对象";是准确的,W3Schools是完全错误的(这并不罕见,它们不好(。函数声明的声明位置与this值无关。当他们用";在一个事件中,这指的是接收到该事件的元素";。

相关内容

最新更新