簡體   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