JavaScript原型函数调用

JavaScript原型函数调用,javascript,Javascript,这是PhoneGap应用程序,但我认为它与此无关。下面是我正在使用的代码: function Geolocation(){ this.maximumAge = 3000; this.timeout = 20; this.enableHighAccuracy = true this.geolocation = navigator.geolocation.getCurrentPosition(this.onSucess, this.onError, {maximum

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

每当触发OneError时,此警报将返回未定义的
。为什么会发生这种情况?

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

这同样适用于成功的
onSuccess

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

如果要在地理位置上下文中运行this.onError,必须使用以下代理方法:

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

proxy(this.onError, this)
例如,请参见:


祝你有一个愉快的一天:-)

除了成功是拼错的这一事实之外,还没有办法确定

JavaScript使用“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);
因此,“这”没有定义

您可以向它传递一个包装器/代理函数,该函数将闭包引用传回您的地理位置对象,以便它可以调用此函数。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
      });
}

这是正确的答案!我很快就会给它做标记。谢谢它是否有任何“副作用”?没有,除了一些浏览器需要为
Function.prototype.bind
(如IE8-)添加垫片之外。您可以在此处找到更多信息和代码:
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
      });
}