1

これはPhoneGapアプリですが、ここでは関係ないと思います。だからここに私が使用しているコードがあります:

function Geolocation(){

    this.maximumAge = 3000;
    this.timeout = 20;
    this.enableHighAccuracy = true
    this.geolocation = navigator.geolocation.getCurrentPosition(this.onSucess, this.onError, {maximumAge : this.maximumAge, timeout : this.timeout, enableHighAccuracy: this.enableHighAccuracy});
}

Geolocation.prototype.onSucess = function(position){
}

Geolocation.prototype.onError = function(error){
    alert( typeof this.onSucess );
}

onError がトリガーされるたびに、このアラートが返されますundefined。なぜそれが起こっているのですか?

4

3 に答える 3

2

this.onError正しいコンテキストで呼び出されていないためです。あなたが試すことができますFunction.bind()

navigator.geolocation.getCurrentPosition(
    this.onSucess.bind(this), 
    this.onError.bind(this),
    //...

についても同様ですonSuccess

于 2013-10-20T14:28:49.833 に答える
1

成功の綴りが間違っているという事実に加えて、まだ確実にする方法はありません。

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
      });
}
于 2013-10-20T14:39:13.770 に答える