javascript - 在 jQuery 按钮回调中获取正确的 "this"

标签 javascript oop this

我有一个类:

function RustEditor() {

this.init = function() {

    var saveButton = this.container.find("button.saveButton");
    saveButton.click(function(){this.save();});

};
...

当我点击按钮时,它会提示 this.save 不是一个函数。这是因为这里的“this”不是指 RustEditor 的实例,而是指按钮。我可以在回调闭包中使用什么变量来指向 RustEditor 的实例?我可以使用 rust.editor(它是全局范围内的名称),但那是难闻的代码。

最佳答案

通常的做法是将 this 值括起来,如下所示:

 function RustEditor() {

 this.init = function() {
    var self = this;

    var saveButton = this.container.find("button.saveButton");
    saveButton.click(function(){self.save();});

 };

根据 tvanfosson 的建议更新: this 在事件处理程序被调用时得到反弹,因此您需要在创建对象时使用一个变量捕获对该类的引用,该变量将在闭包中保留该引用。

关于javascript - 在 jQuery 按钮回调中获取正确的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1128063/

相关文章:

javascript - 为什么这是 javascript 的输出?

javascript - ScrollFire 插件似乎无法正常工作

javascript - 在javascript中的document.getElementByid中传递变量

javascript - 如何从jQuery中的类中选择没有标签的子元素

java - 面向对象设计和数据库设计过程

c++ - 从函数返回 this 指针的重要用途是什么?

c# - 如何在asp.net中动态生成HTML和CSS?

c# - 在 C# 中使用工厂设计模式的示例

javascript - JS中使用OOP的几种格式

java - "this"如何从已发布的内部类中逃逸