【发布时间】:2020-06-19 02:57:28
【问题描述】:
请考虑以下代码。
<!DOCTYPE html>
<title>Question</title>
<script>
function report(handler, _this) {
alert(
"handler:\n" + handler + "\n" +
"this: " + _this + "\n" +
"event: " + event + "\n"
)
}
</script>
<input type=button id=A value=A onclick="report(A.onclick, this)">
<script>function f() {report(B.onclick, this)}</script>
<input type=button id=B value=B onclick="f()">
<input type=button id=C value=C>
<script>C.onclick = function () {report(C.onclick, this)}</script>
通过点击按钮,我看到了:
-
A.onclick和B.onclick被包裹在 "function onclick(事件) {...}"。 - 在
B.onclick,this是窗口 (而不是按钮)。
还有其他注意事项吗?
【问题讨论】:
-
由于 JavaScript 作用域,Note 事件在
report中定义。 -
您想查看 javascript 中的事件循环。 javascript 中的所有事件都是异步的。因为它们是异步的,所以它们被窗口对象回调。研究 javascript 和事件循环中的异步操作来理解这个概念。
-
在A.onclick和C.onclick中,
this是一个按钮;据推测,f 是绑定到窗口的,因为它是在脚本的顶层定义的。 -
通常事件中的回调函数绑定到触发事件的元素的对象。但是在 B 的情况下,回调函数被包装在一个函数中并且它失去了它的上下文。
-
这能回答你的问题吗? How does the "this" keyword work?