[英]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”不是由方法的定義決定的,而是由它如何被調用決定的。
我最近在另一個類似問題中解釋了這一點
例如,我可以定義一個指向您的函數的變量:
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)
例如看到這個:
祝你今天愉快 :-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.