2017-07-02 22 views
0

私は以下のクラスを持っています。 this.handlersでこの参照(ライン2)this.setTimeRange(4行目)に、この異なっているので、それは私がコールバック関数からクラスメソッドを呼び出すことができますどのようにコールバック関数内のコールバックメソッド

function Synchronized() { 
    this.handlers = []; 
    $("#masterSlider").rangeSlider(); 

    $("#masterSlider").bind("valuesChanging", function(e, data) { 
     this.setTimeRange(data.values.min, data.values.max); 
    }); 

} 

Synchronized.prototype = { 
    setTimeRange: function(lowerBound, upperBound) { 
     console.log(lowerBound, upperBound); 
     this.lowerBound = lowerBound; 
     this.upperBound = upperBound; 
     $("#masterSlider").rangeSlider("bounds", this.lowerBound, this.upperBound); 
    }, 
} 

をバグを持っていますか?

答えて

0

いくつかの選択肢があります。最も一般的な3つのもの:

thisの指定された値を持つ別の関数を返すために、あなたが使用function.prototype.bind

var that = this; 
$("#masterSlider").bind("valuesChanging", function(e, data) { 
    that.setTimeRange(data.values.min, data.values.max); 
}); 

の上に無名関数に閉じることができ thisのコピーを格納する変数を作成します。

$("#masterSlider").bind("valuesChanging", (function(e, data) { 
    this.setTimeRange(data.values.min, data.values.max); 
}).bind(this)); 

代わりに無名関数のES6矢印機能を使用します。

$("#masterSlider").bind("valuesChanging", (e, data) => this.setTimeRange(data.values.min, data.values.max)); 
+0

既にリンクされている場合は、重複してフラグを付けてください。 – Li357

1

コールバックに入力して参照を失う前に、関数参照を保存する必要があります。 1つの解決策は次のようなものです:

var self = this; 
    $("#masterSlider").bind("valuesChanging", function(e, data) { 
    self.setTimeRange(data.values.min, data.values.max); 
}); 
関連する問題