javascript - 在 onclick 事件的上下文中, "this"是如何工作的? (JavaScript)

标签 javascript html

<分区>

我了解 this 在对象上调用时的工作原理,但我无法理解 this 从“静态”上下文调用时的工作原理。

给定以下 HTML:

<body onload="myOnLoad()">
    <div id="someDiv">0</div>
</body>

...和这个 javascript:

function myOnLoad() {
    var inc = new Incrementer();
    /*** increase() works fine here, "this" refers to "inc" ***/
    inc.increase();
    inc.setOnClick();
}

function Incrementer() {
    this.value = 0;
}

Incrementer.prototype.setOnClick = function() {
    /*** increase fails to update someDiv when clicked.
         "this" is not "inc"   ***/
    document.getElementById("someDiv").onclick = this.increase;
}

Incrementer.prototype.increase = function() {
    document.getElementById("someDiv").innerHTML = ++this.value;
}

...点击 someDiv 将它的 innerHTML 变成 NaN。我意识到这是因为 onclick 事件不知道 inc 的存在,但我不明白的是如何将 'inc' 传递给 onclick 事件。

你知道我如何从 onclick 的上下文中访问 inc 的变量吗?或者,是否有更传统的方法来执行此操作?

我最感兴趣的是了解如何使 someDiv 的 onclick 指向特定实例 inc

最佳答案

this 指的是调用函数的上下文,例如在 setOnClick 中,函数 this.increase 将在 someDiv 的上下文中调用,因此 this.value 将是在这种情况下未定义。

尝试

document.getElementById("someDiv").onclick = this.increase.bind(this);

您可能想从此处了解有关 this 属性的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

关于javascript - 在 onclick 事件的上下文中, "this"是如何工作的? (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33992006/

相关文章:

javascript - 使用 Ajax 在 Gridview 更新后显示工具提示

ipad - 如何使 iPad 上 HTML5 视频侧面的黑条消失?

css - 想要使用 flexbox 在图像上叠加一个 div

html - 如何让 div、header、container 等覆盖视口(viewport)

javascript - 如何在动态设置时(在超时内)使列表项尊重 ul padding-right

charts - 人力车-js图表库: Need strings instead of numbers on axes

javascript - fancybox:找到调用 fancybox 的 anchor

javascript - 访问用于创建 html 页面的文件夹和文件

javascript - Node.js 视频的完整路径

javascript - 缓存 AJAX 请求