类和属性问题
Class and attribute problem
我想在我的Android上玩地理定位API。我知道有一个已定义的"navigator"对象,它应该用于获取用户位置。因此,我创建了这个示例代码:
function GeolocationTester()
{
// here I want to store all acquired locations
this.locations = new Array();
alert("this.locations defined: " + this.locations);
this.onSuccess = function(position)
{
alert("Entered onSuccess");
alert("this.locations defined: " + this.locations);
}
this.onError = function(error)
{
alert("error acquiring location");
}
navigator.geolocation.watchPosition(this.onSuccess, this.onError, { enableHighAccuracy: true });
}
这对我不起作用。每次watchPosition调用成功的这个。locations字段没有定义(它是在new Array之后定义的)。我知道我做错了什么,但因为这是我的JavaScript尝试之一,不确定什么。有人发现问题了吗?
问题在于this
的范围。当调用onSuccess
或onError
时,this
不绑定到包含locations
数组的对象。您需要在函数之外创建一个显式变量,数组应该分配给该变量,然后在回调中使用该变量,如下所示:
var allLocations = this.locations = [a, b, c];
this.onSuccess = function(position) {
alert("allLocations: " + allLocations);
alert("this.locations: " + this.locations);
}
这是你使用this
的原因。这将会改变,因为它取决于你的函数调用的上下文。只需使用函数的作用域来声明location:
function GeolocationTester()
{
// here I want to store all acquired locations
var locations = [];
alert("locations defined: " + locations);
function onSuccess(position) {
alert("Entered onSuccess");
alert("locations defined: " + locations);
}
function onError(error){
alert("error acquiring location");
}
navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true });
}
要真正了解this
,请阅读这篇博文http://dmitrysoshnikov.com/ecmascript/chapter-3-this/
尝试这样定义onSuccess
:
this.onSuccess = (function(locations) {
return function(position)
{
alert("Entered onSuccess");
alert("this.locations defined: " + locations);
}
})(this.locations);
相关文章:
- JavaScript Pub/Sub属性访问问题
- 使用导航属性创建Kendo UI网格模型的问题
- 使用jQuery设置HTML5属性值时出现问题
- 将输入值设置为ng模型属性[Angular]时出现问题
- 我该如何解决这个问题?“未捕获的类型错误:无法读取 null 的属性'appendChild'”
- 奇怪的数据属性布尔问题
- 此属性检索代码有什么问题
- 访问模板中的属性时出现问题-除'name'显示错误'没有定义[attributename];
- 关于JavaScript对象结构属性的问题
- 句柄中包含括号的问题处理属性
- JSSOR Slider中的空幻灯片和goto-currentIndex属性在javascript中不起作用的问题
- HTML:密码字段中的HTML5占位符属性问题 - 显示正常文本
- SJCL的问题“;无法读取属性'替换'“未定义”;
- 页面速度 - 仅使用 defer 属性的任何问题
- 使用多个 css 类将 css 转换属性应用于 DOM 对象时遇到问题
- JavaScript - 对象/属性中的区分大小写问题
- 在 XSLT 工作表中的 JavaScript 中插入属性的问题
- 使用此 javascript 在 IE7 中收到“对象不支持此属性或方法”错误,以及选项卡未正确定位的问题
- 内容可编辑属性的问题
- 渲染 WebGL 时特定于 Windows 的问题.属性设置为零