这是我第一次使用 JS 对象,我很困惑为什么这个属性总是未定义:
function Rotator() {
this.interval = 300;
this.image = 0;
this.images = undefined;
}
Rotator.prototype.Fetch = function(links) {
console.log("Fetch called");
this.images = links;
}
Rotator.prototype.Current = function() {
if (this.images == undefined) {
console.log("Error, images is undefined");
}
return this.images[this.image];
}
r = new Rotator;
$.getJSON("./data.php", function (data) {
r.Fetch(data.images);
});
console.log(r.Current());
我得到的错误是:
未捕获的类型错误:无法读取未定义的属性“0”
返回的 JSON 工作正常,并且在控制台中将 fetch 标记为已调用(记录时数据也很好)。为什么 Rotator.images 总是未定义?
编辑:一些 console.log 结果:
- 登录
data.images
会$.getJSON
产生正确的数据。 - 登录
links
会Fetch
产生正确的数据。 - 登录
this.images
会Fetch
产生正确的数据。 - 登录结果
this.images
为Current
空。