提问人:Ratan Nampalle 提问时间:7/21/2021 最后编辑:Ratan Nampalle 更新时间:7/21/2021 访问量:216
为什么/如何“this”关键字指的是事件对象而不是全局对象,因为我在函数中使用了“this”关键字 [duplicate]
why/how is 'this' keyword referring to event object and not global object as I have used 'this' keyword in a function [duplicate]
问:
我做了什么:
- 将事件侦听器添加到 type = “button” 的所有 div
- 当用户点击任何按钮时,我使用“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”关键字的理论:根据使用位置的不同,它具有不同的值:
- 在方法中,这是指所有者对象。
- 单独而言,这是指全局对象。
- 在函数中,这是指全局对象。
- 在函数中,在严格模式下,这是未定义的。
- 在事件中,这是指接收事件的元素。
真正的问题:解释为什么“this”关键字指的是事件对象而不是全局对象,因为我在函数 userClick() 中使用了“this”关键字
答:
1赞
Quentin
7/21/2021
#1
函数中的值由函数的调用方式决定。this
你不是在调用函数,而是将它传递给浏览器,然后浏览器调用它(并分配正在侦听的元素作为值)。addEventListener
this
这就是设计的方式。addEventListener
为什么“this”关键字指的是事件对象而不是全局对象,因为我在函数 userClick() 中使用了“this”关键字
假设你的引用“在一个函数中,这指的是全局对象”是准确的,那么W3Schools是完全错误的(这并不罕见,它们并不好)。声明函数的位置与值无关。当他们与“在事件中,这是指接收事件的元素”自相矛盾时,他们就正确了。this
评论
this
this
this