javascript – 在jQuery按钮回调中获得正确的“this”

前端之家收集整理的这篇文章主要介绍了javascript – 在jQuery按钮回调中获得正确的“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(它在全局范围内的名称),但这是臭臭的代码.

解决方法

通常的做法是将这个值括起来:

function RustEditor() {

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

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

 };

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

猜你在找的jQuery相关文章