JavaScript 原型函数调用

JavaScript prototype function call

本文关键字:函数调用 原型 JavaScript      更新时间:2023-09-26

这是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"不是由方法的定义决定的,而是由它的调用方式决定的。

我最近在另一个类似的问题中解释了这一点:

"这个"如何影响方法的方法?

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

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

因此没有定义"这个"。

你可以做的是将一个包装器/代理函数传递给它,该函数具有对地理位置对象的闭包引用,以便它可以调用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 的上下文中运行。

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

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

用法:

proxy(this.onError, this)

例如,请参阅以下内容:

http://jsfiddle.net/Z32BZ/

祝你有美好的一天:-)