我有一些示例代码如下:
var myDrawingArea = new DrawingArea(document.getElementById("drawing_canvas"));
function DrawingArea(aCanvas) {
this.brushSize = 2;
this.buildToolbar = (function () {
$("#brush-size")
.slider({
value: this.brushSize, // this is DrawingArea instance
slide: function (event, ui) {
//*************** PROBLEM ***************
// this is referring to the slider DOM element not my DrawingArea instance
// how can I access both the outer "this" and the inner one?
this.brushSize = ui.value;
$(this).find(".ui-slider-handle").text(this.brushSize);
}
})
.find(".ui-slider-handle").text(this.brushSize);
});
}
正如评论中所说,“我如何才能访问外部”这个“内部”和“内部”?
答案 0 :(得分:0)
您可以存储对它的引用,如下所示:
function DrawingArea(aCanvas) {
var self = this;
self.brushSize = 2;
self.buildToolbar = (function () {
$("#brush-size")
.slider({
value: self.brushSize,
slide: function (event, ui) {
self.brushSize = ui.value;
$(this).find(".ui-slider-handle").text(self.brushSize);
}
})
.find(".ui-slider-handle").text(this.brushSize);
});
}
你可以在this
回调之外使用self
或 slide
,但我认为保持一致更为清晰。< / p>