Javascript和jQuery得到了正确的答案

时间:2010-09-30 15:38:08

标签: javascript jquery object scope this

我有一些示例代码如下:

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);
    });
}

正如评论中所说,“我如何才能访问外部”这个“内部”和“内部”?

1 个答案:

答案 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>