首页 > 解决方案 > 我的代码可以使用和不使用函数参数,我不明白为什么:

问题描述

// 这是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);

两种代码都有效,但下面的代码不必在函数参数中接受事件,所以我想知道为什么。是否有其他原因?

标签: javascript

解决方案


这是其中一种“巧合”的情况,但这绝对不是事件的处理方式。

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

您应避免在新代码中使用此属性,而应使用传递给事件处理函数的事件。此属性并未得到普遍支持,即使受支持也会给您的代码带来潜在的脆弱性。


推荐阅读