Using jQuery with classes from ES6

Using jQuery with classes from ES6

本文关键字:from ES6 classes with jQuery Using      更新时间:2023-09-26

我刚刚在新项目中遇到了一个小问题。基本上,作为页面的一部分,有一个帖子页面和一些来自后端的评论。我想做的就是为这些提供一些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回调样式。当我将类成员传递给jQuery回调时,在调用中,jQuery模拟其上下文,因此thisspan.reply,而不是Comment实例。重点是我希望能够达到实际的评论实例。

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

您可以使用.bind 为函数定义this对象

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

在您的情况下

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