< button id = "elem" > Click me < /button>

  <
  script >
  class Menu {
    handleEvent(event) {
      // mousedown -> onMousedown
      let method = 'on' + event.type[0].toUpperCase() + event.type.slice(1);
      this[method](event);
    }

    onMousedown() {
      elem.innerHTML = "Mouse button pressed";
    }

    onMouseup() {
      elem.innerHTML += "...and released.";
    }
  }

let menu = new Menu();
elem.addEventListener('mousedown', menu);
elem.addEventListener('mouseup', menu); <
/script>

有人能帮我理解这段代码中的内容吗?非常感谢.

 handleEvent(event) {
       // mousedown -> onMousedown
       let method = 'on' + event.type[0].toUpperCase() + event.type.slice(1);
       this[method](event);
    }

推荐答案

event.type[0].toUpperCase()  -- this will return first character of your event name in upper case.(e.g. for submit event, it will return `S` )

event.type.slice(1) -- this will return you all characters of event name except first character.  (e.g. for submit event , it will return `ubmit`)

那么你在上面加on.

在函数的最后一行之后,您将调用从上述字符串生成的派生函数,例如onSubmit.

在您的情况下,看起来您正在捕获mousedown个事件&;然后将该事件转换为onMousedown()字符串(&;调用onMousedown()方法.

Javascript相关问答推荐

数字时钟在JavaScript中不动态更新

如何从隐藏/显示中删除其中一个点击?

为什么Mutations 观察器用微任务队列而不是macrotask队列处理?

当使用';字母而不是与';var#39;一起使用时,访问窗口为什么返回未定义的?

为什么123[';toString';].long返回1?

正则表达式,允许我匹配除已定义的子字符串之外的所有内容

让chart.js饼图中的一个切片变厚?

在VS代码上一次设置多个变量格式

未捕获的运行时错误:调度程序为空

是否可以将异步调用与useState(UnctionName)一起使用

react -原生向量-图标笔划宽度

MongoDB中的嵌套搜索

Reaction路由v6.4+数据API:重试加载程序而不显示错误

Js问题:有没有办法将数据从标记表转换成图表?

Tinymce CREATE COMMENT函数不读取更新状态

如何在 map 中显示美国州/加拿大省的缩写-第1部分?

使用滚动页边距顶部的JavaScript平滑滚动在结尾处创建跳转

如何在Xbox中撤销令牌

VUE 3数据未恢复

如何在chart.js中绘制向后弯曲线