javascript - 我的代码可以使用和不使用函数参数,我不明白为什么:
问题描述
// 这是Codecademy上的一个练习,我是按照步骤操作的,遇到了这种情况。
//这是教程中的代码
// Write a named function with event handler properties
const keyPlay = (event) =>{
event.target.style.backgroundColor = 'green';
}
const keyReturn = (event) =>{
event.target.style.backgroundColor = '';
}
// Write a named function with event handler properties
let assignEvents = (note) =>{
note.onmousedown = () =>{
keyPlay(event);
}
note.onmouseup = ()=>{
keyReturn(event);
}
}
// Write a loop that runs the array elements through the function
notes.forEach(assignEvents);
2.不是教程
// Write named functions that change the color of the keys below
const keyPlay = () =>{
event.target.style.backgroundColor = 'green';
}
const keyReturn = () =>{
event.target.style.backgroundColor = '';
}
// Write a named function with event handler properties
let assignEvents = (note) =>{
note.onmousedown = () =>{
keyPlay();
}
note.onmouseup = ()=>{
keyReturn();
}
}
// Write a loop that runs the enter code herearray elements through the functionenter code here
notes.forEach(assignEvents);
两种代码都有效,但下面的代码不必在函数参数中接受事件,所以我想知道为什么。是否有其他原因?
解决方案
这是其中一种“巧合”的情况,但这绝对不是事件的处理方式。
来自MDN:
只读 Window 属性事件返回当前由站点代码处理的事件。在事件处理程序的上下文之外,该值始终是未定义的。
因此,当从闭包外部调用时event
,您实际上指的是window.event
. 如上所述,这将在事件处理程序的上下文中返回当前发生的事件。
作为函数参数传递event
,然后在该函数中引用它将引用参数本身,而不是event
全局范围内的属性(即window
)。它有点像事件处理程序上下文的静态属性。
通过更改参数名称更容易证明这一点:
// Write a named function with event handler properties
const keyPlay = (playEvent) =>{
playEvent.target.style.backgroundColor = 'green';
}
// works as expected!
// Write a named function with event handler properties
const keyPlay = () =>{
playEvent.target.style.backgroundColor = 'green';
}
// Exception: playEvent is undefined
// (and there's no `window.playEvent` to accidentally reference instead)
但是,您应该将事件作为参数传递,因为根据 MDN(再次):
您应避免在新代码中使用此属性,而应使用传递给事件处理函数的事件。此属性并未得到普遍支持,即使受支持也会给您的代码带来潜在的脆弱性。
推荐阅读
- gradle - 我可以在不使用 apply from 的情况下执行另一个 gradle 文件吗(比如根本不修改实际的 build.gradle)?
- testing - TestCafe:单页应用程序的页面模型
- python - 停止在 python 的 prometheus_client 中抓取默认指标
- r - 从 Google Drive 文件夹中读取多个 CSV 文件,然后附加到 R 中的单个文件中
- html - 在 Angular 的表头中使用 FontAwesome 图标
- ruby-on-rails - 如何设置一个枚举以允许查询中的多个枚举?GraphQL 红宝石
- spring - ObjectMapper.readTree 返回 ObjectNode/TextNode 而不是 DecimalNode
- python - 检测图像中的细线
- c# - 当已经在学生实体中时,大摇大摆地为学生创建一个额外的定义
- azure-databricks - 在工作时间启动 Azure Databricks 群集