英文:
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('saving');
}
load() {
alert('loading');
}
search() {
alert('searching');
}
onClick(event) {
let action = event.target.dataset.action;
if (action) {
this[action]();
}
};
}
new Menu(menu);
<!-- language: lang-html -->
<div id="menu">
<button data-action="save">Save</button>
<button data-action="load">Load</button>
<button data-action="search">Search</button>
</div>
<!-- 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论