繁体   English   中英

JavaScript原型函数调用

[英]JavaScript prototype function call

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

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

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

onSuccess

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

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

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

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

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

用法:

proxy(this.onError, this)

例如看到这个:

http://jsfiddle.net/Z32BZ/

祝你今天愉快 :-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM