JavaScript:关于在类中使用bind的问题

huangapple go评论51阅读模式
英文:

Javascript: question on use of bind in a class

问题

这是我的理解,以下代码需要使用 bind(this, ...),因为 this.onClick 在 (*) 中被绑定到了当前对象。这很重要,否则其中的 this 将引用DOM元素(elem),而不是Menu对象,而 this[action] 将不会是我们需要的内容。

可以有人进一步解释吗?我对 this.onClick 真正表示 elem.onClick 以及为什么感到困惑。

英文:

It's my understanding the following code requires bind(this,...) because this.onClick is bound to this in (*). That’s important, because otherwise this inside it would reference the DOM element (elem), not the Menu object, and this[action] would not be what we need.

Can someone explain this further? Confused how this.onClick really represents elem.onClick and why.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

class Menu {
  constructor(elem) {
    this._elem = elem;
    elem.onclick = this.onClick.bind(this); // (*)
  }

  save() {
    alert(&#39;saving&#39;);
  }

  load() {
    alert(&#39;loading&#39;);
  }

  search() {
    alert(&#39;searching&#39;);
  }

  onClick(event) {
    let action = event.target.dataset.action;
    if (action) {
      this[action]();
    }
  };
}

new Menu(menu);

<!-- language: lang-html -->

&lt;div id=&quot;menu&quot;&gt;
  &lt;button data-action=&quot;save&quot;&gt;Save&lt;/button&gt;
  &lt;button data-action=&quot;load&quot;&gt;Load&lt;/button&gt;
  &lt;button data-action=&quot;search&quot;&gt;Search&lt;/button&gt;
&lt;/div&gt;

<!-- end snippet -->

答案1

得分: 1

onXXX事件字段已被弃用,不应使用,因为存在脚本注入的问题。相反,请使用addEventListener并使用ContentSecurityPolicy(禁用onXXX事件绑定)。

英文:

The onXXX event fields are deprecated and should not be used because of the problem with script injection. Instead, use addEventListener and use a ContentSecurityPolicy (which disables onXXX event binding)

huangapple
  • 本文由 发表于 2023年7月13日 23:34:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76681137.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定