使用ES6箭头函数设置事件侦听器

Set event listener with ES6 arrow functions

本文关键字:设置 事件 侦听器 函数 ES6 使用      更新时间:2023-09-26

问题:为什么没有设置事件侦听器?

//ADDING THE EVENT LISTENER
document.addEventListener('DOMContentLoaded', init);
//DELCARING INIT, PASSING BLANK PARAM, STATEMENT
var init = () => console.log('Is Firing');

在使用init之前,应该先声明它。

//DELCARING INIT, PASSING BLANK PARAM, STATEMENT
var init = () => alert('Is Firing');
//ADDING THE EVENT LISTENER
document.addEventListener('DOMContentLoaded', init);

init是一个函数表达式,这意味着它不会发生提升,因此您应该在侦听器绑定之前拉起函数表达式。我建议你研究一下功能提升。https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/function#Function_declaration_hoisting