gpt4 book ai didi

javascript - 我的代码使用和不使用函数参数,我不明白为什么 :

转载 作者:搜寻专家 更新时间:2023-11-01 04:34:29 27 4
gpt4 key购买 nike

//这是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 :

The read-only Window property event returns the Event which is currently being handled by the site's code. Outside the context of an event handler, the value is always undefined.

因此,当从闭包外部调用 event 时,您实际上指的是 window.event。如上所述,这将返回事件处理程序上下文中当前发生的事件。

event 作为函数参数传递,然后在该函数中引用它会引用参数本身,而不是全局范围内的 event 属性(即 窗口)。它有点像事件处理程序上下文的静态属性。

通过更改参数名称可以更轻松地证明这一点:

// 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(再次):

You should avoid using this property in new code, and should instead use the Event passed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code.

关于javascript - 我的代码使用和不使用函数参数,我不明白为什么 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57663040/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com