在 ES6 中使用 jQuery 和 类

Using jQuery with classes from ES6

我的新项目刚刚遇到了一个小问题。基本上,有一个 post 页面和一些来自后端的评论作为页面的一部分。我想做的就是为这些提供一些 JavaScript 逻辑。我所做的提供:

class Comment {
    constructor(comment) {
        console.log("Creating comment object...");
        $(comment).find(".vote").click(this.toggle_vote);
        $(comment).find(".action.reply").click(this.toggle_reply);
    }

    toggle_vote() {
        // Context here is `span.reply`, not Comment instance,
        // but I want to access class members
        if ($(this).is(".voted")) {
            $(this).removeClass("voted");
            return;
        }

        $(this).addClass("voted");
        $(this).siblings().first().removeClass("voted");
    }

    // ...
}

下面的问题在于jQuery回调风格。当我将 class 成员传递给 jQuery 回调时,在调用中,jQuery 模拟其上下文,因此 thisspan.reply,而不是 Comment 实例.关键是我希望能够到达实际的 Comment 实例。

免责声明:我根本不是前端人员,所以我可能需要一些严格的解释来解决这个问题,谢谢!

您可以使用 .bind 为函数定义 this-object

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

你的情况

.click(this.toggle_vote.bind(this))