[英]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.