JavaScript原型函数调用

时间:2013-10-20 14:25:08

标签: javascript

这是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。为什么会这样?

3 个答案:

答案 0 :(得分:2)

因为没有使用正确的上下文调用this.onError。您可以尝试Function.bind()

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

onSuccess同样如此。

答案 1 :(得分:1)

除了成功拼错之外,还没有办法确定。

JavaScript使用“this”的棘手问题是“this”不是由方法的定义决定的,而是由它的调用方式决定的。

我最近在另一个类似的问题中对此进行了解释:

How the "this" affected in a method's method?

例如,我可以定义一个指向您的函数的变量:

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
      });
}

答案 2 :(得分:0)

this.onError 正在另一个上下文中运行。它在 navigator.geolocation 的上下文中运行。

如果要在 Geolocation 的上下文中运行 this.onError ,则必须使用如下代理方法:

proxy = function(func, context) {
     func.apply(context);   
}

用法:

proxy(this.onError, this)

例如见:

http://jsfiddle.net/Z32BZ/

度过美好的一天: - )