[英]Problems in accessing global variables
我在訪問附加到javascript窗口中的全局變量時遇到一些問題。 這是我使用腳本標記嵌入到索引頁面中的代碼片段,可以說
var Geolocation = function() {
var self = this;
self.errors = {
TIMEOUT: 1,
POSITION_UNAVAILABLE: 2,
PERMISSION_DENIED: 3,
UNKNOWN_ERROR: 4
};
self.getCurrentPosition = function( success, error, options ) {
// simulate the wait for the user choice
var geoIntervalId = window.setInterval(function( ) {
if ( state != null ) {
window.clearInterval(geoIntervalId);
switch( state ) {
case 'ok':
success(new Position(latitude, longitude));
break;
case 'timeout': case 'position_unavailable': case 'permission_denied':
error( new GeolocationError( self.errors[state.toUpperCase()] ) );
break;
default:
error( new GeolocationError( self.errors.UNKNOWN_ERROR ) );
}
}
}, 100); // ms
};
}
var Position = function( lat, lng ) {
this.coords = new Coordinates(lat, lng);
}
var Coordinates = function( lat, lng ) {
this.latitude = lat;
this.longitude = lng;
}
var GeolocationError = function( code ) {
this.TIMEOUT = 1;
this.POSITION_UNAVAILABLE = 2;
this.PERMISSION_DENIED = 3;
this.UNKNOWN_ERROR = 4;
this.code = code;
}
var state = null,
latitude = null,
longitude = null;
window.geolocation_provider = new Geolocation();
之后,我再次使用腳本標記在索引文件中包含另一個javascript文件,例如test.js。 現在,當我嘗試訪問window.geolocation_provider變量時,結果為null。 為什么會這樣
嘗試這個
(function(window){
var Geolocation = function() {
var self = this;
self.errors = {
TIMEOUT: 1,
POSITION_UNAVAILABLE: 2,
PERMISSION_DENIED: 3,
UNKNOWN_ERROR: 4
};
self.getCurrentPosition = function( success, error, options ) {
// simulate the wait for the user choice
var geoIntervalId = window.setInterval(function( ) {
if ( state !== null ) {
window.clearInterval(geoIntervalId);
switch( state ) {
case 'ok':
success(new Position(latitude, longitude));
break;
case 'timeout': case 'position_unavailable': case 'permission_denied':
error( new GeolocationError( self.errors[state.toUpperCase()] ) );
break;
default:
error( new GeolocationError( self.errors.UNKNOWN_ERROR ) );
}
}
}, 100); // ms
};
};
var Position = function( lat, lng ) {
this.coords = new Coordinates(lat, lng);
};
var Coordinates = function( lat, lng ) {
this.latitude = lat;
this.longitude = lng;
};
var GeolocationError = function( code ) {
this.TIMEOUT = 1;
this.POSITION_UNAVAILABLE = 2;
this.PERMISSION_DENIED = 3;
this.UNKNOWN_ERROR = 4;
this.code = code;
};
var state = null,
latitude = null,
longitude = null;
if(window.geolocation_provider === undefined){
window.geolocation_provider = new Geolocation();
}
})(window ? window : this)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.