【问题标题】:How do I get "this" into this function... jquery slider [duplicate]我如何将“这个”放入这个函数中...... jquery滑块[重复]
【发布时间】:2014-01-14 01:50:23
【问题描述】:

我有类似以下的内容:

MyShape = function() {

    var _container = {
        width: 100,
        height: 100
    }


    this.draw() { 
       //do stuff...
    }

    $('#slider-1').bind('change', function(event, ui) {

        _container.width = $('#slider-1').val();
        this.draw();

    });


};

我正在使用 jquery 滑块来动态更改形状的宽度,然后我调用 .draw() 来重绘形状。我不断收到此错误:

Uncaught TypeError: Object # has no method 'draw'

我很确定这是因为我需要将上下文“this”传递给 change 函数,但我似乎不知道该怎么做。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    这是因为JavaScript's this is dynamic.

    你可以像这样使用Function.prototype.bind

    $('#slider-1').on('change', function(event, ui) {
    
        _container.width = $('slider-1').val();
        this.draw();
    
    }.bind(this) /* use the same this value */);
    

    或者你可以使用闭包变量

    var that = this;
    $('#slider-1').on('change', function(event, ui) {
    
        _container.width = $('slider-1').val();
        that.draw();
    
    });
    

    【讨论】:

    • 还有$.proxy,不过我认为bind在这个例子中更干净。
    • @Benjamin - 很好的及时编辑;我要指出你需要使用.on :)
    • @Tyblitz: .on() 可能是首选,但不是必需的。
    • @user602525:请注意,第一个示例中使用的 Function.prototype.bind() 在 IE8 及更低版本以及其他一些较旧的浏览器中不可用。
    • .bind 只是别名on。这是它的完整源代码function(types, data, fn) { return this.on(types, null, data, fn);}。最好使用.on,因为它是较新的界面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    相关资源
    最近更新 更多