Bar*_*lom 3 javascript oop this
我有一节课:
function RustEditor() {
this.init = function() {
var saveButton = this.container.find("button.saveButton");
saveButton.click(function(){this.save();});
};
...
Run Code Online (Sandbox Code Playgroud)
当我单击按钮时,它会抱怨this.save不是一个函数.这是因为"this"不是指这里的RustEditor实例,而是指按钮.我可以在回调闭包内使用什么变量来指向RustEditor的实例?我可以使用rust.editor(它在全局范围内的名称),但这是臭臭的代码.
set*_*eth 12
通常的做法是将this值括起来:
function RustEditor() {
this.init = function() {
var self = this;
var saveButton = this.container.find("button.saveButton");
saveButton.click(function(){self.save();});
};
Run Code Online (Sandbox Code Playgroud)
根据tvanfosson的建议更新:
this在调用事件处理程序时获取反弹,因此您需要在创建对象时使用将在闭包中保留该引用的变量捕获对类的引用.