2014-01-13 36 views
2

我有類似以下內容:我如何得到「這個」這個功能... jQuery的滑塊

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'

我相當肯定,那是因爲我需要通過上下文「本」到變化的功能,但我似乎無法弄清楚如何做到這一點。

回答

9

這是因爲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(); 

}); 
+1

同樣['$ .proxy'(http://api.jquery.com/ jQuery.proxy /),但是,我認爲在這個例子中'bind'更清晰。 – crush

+2

@Benjamin - 很好的及時編輯;我要指出,你需要使用'.on' :) – Tyblitz

+1

工作感謝 – user602525