我有类似以下内容:
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();
});
};
Run Code Online (Sandbox Code Playgroud)
我正在使用jquery滑块动态地改变我的形状的宽度,然后我调用.draw()来重绘形状.我不断收到此错误:
未捕获的TypeError:对象#没有方法'draw'
我很确定这是因为我需要将上下文"this"传递给change函数,但我似乎无法弄清楚如何做到这一点.
这是因为JavaScript this是动态的.
您可以这样使用Function.prototype.bind:
$('#slider-1').on('change', function(event, ui) {
_container.width = $('slider-1').val();
this.draw();
}.bind(this) /* use the same this value */);
Run Code Online (Sandbox Code Playgroud)
或者您可以使用闭包变量
var that = this;
$('#slider-1').on('change', function(event, ui) {
_container.width = $('slider-1').val();
that.draw();
});
Run Code Online (Sandbox Code Playgroud)