繁体   English   中英

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

[英]my code works with and without function parameters, and I don't understand why:

//这是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。 在事件处理程序的上下文之外,该值始终未定义。

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

event作为函数参数传递,然后在该函数中引用它将引用参数本身,而不是全局范围(即window )上的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(再次):

您应该避免在新代码中使用此属性,而应该使用传递给事件处理函数的Event。 此属性不受普遍支持,即使支持也会导致代码的潜在脆弱性。

有两种可能性:

  1. event是一个全局变量。 因此,当你编写event.target.style.backgroundColor = 'green'; ,该全局变量的属性发生了变化。

  2. 第二个代码块没有正确编译,第一个块仍然是正在运行的。 我认为没有传递事件,则event.target.style.backgroundColor = 'green'; 引用一个未知对象,因此在编译时会失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM