成功の綴りが間違っているという事実に加えて、まだ確実にする方法はありません。
JavaScript での "this" の使用に関するトリッキーな点は、"this" がメソッドの定義ではなく、どのように呼び出されるかによって決定されることです。
私は最近、別の同様の質問でこれを説明しました:
「this」はメソッドのメソッドにどのように影響しましたか?
たとえば、関数を指す変数を定義できます。
var blah = this.onSucess;
blah(); // "this" will be undefined
var bleh = {
test: this.onSuccess
}
bleh.test(); // "this" will be the object literal.
getCurrentPosition がコールバック関数を呼び出す場合、おそらく直接呼び出すだけです。
onSuccess(position);
したがって、「これ」は定義されていません。
あなたができることは、Geolocation オブジェクトへのクロージャー参照を持つラッパー/プロキシ関数を渡すことです。これにより、this.onSuccess を呼び出すことができます。
function Geolocation(){
this.maximumAge = 3000;
this.timeout = 20;
this.enableHighAccuracy = true
this.geolocation = navigator.geolocation.getCurrentPosition(function (position) {
this.onSucess(position);
},
function (error) {
this.onError(error);
},
{
maximumAge : this.maximumAge,
timeout : this.timeout,
enableHighAccuracy: this.enableHighAccuracy
});
}
David が示したように、これを行う簡単な方法は、Function.bind を使用することです。これは、私が説明したとおりのラッパー関数を返します。
function Geolocation(){
this.maximumAge = 3000;
this.timeout = 20;
this.enableHighAccuracy = true
this.geolocation = navigator.geolocation.getCurrentPosition(this.onSucess.bind(this),
this.onError.bind(this),
{
maximumAge : this.maximumAge,
timeout : this.timeout,
enableHighAccuracy: this.enableHighAccuracy
});
}