0

这是我第一次使用 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产生正确的数据。
  • 登录linksFetch产生正确的数据。
  • 登录this.imagesFetch产生正确的数据。
  • 登录结果this.imagesCurrent空。
4

3 回答 3

2

因为获取 JSON 是异步的,所以数据只在回调函数中可用。

$.getJSON("./data.php", function (data) { // callback function
    r.Fetch(data.images); // this will run when the data is available
});

console.log(r.Current()); // this will run immediately -> data.images is null

一切依赖于数据的东西都应该放在回调函数中!

于 2010-07-05T13:58:37.770 回答
0

Will this get me purists on my neck or is it acceptable?

Rotator.prototype.Current = function() {
    if (this.images) return this.images[this.image];
    console.log("Error, images is undefined, null, empty or 0");
}
于 2010-07-05T14:01:30.780 回答
0

你不能用undefined那种方式。改用null

this.images = null;

if (this.images == null) {

编辑:

如果它为空,您还必须避免使用 images 属性:

Rotator.prototype.Current = function() {
  if (this.images == null) {
    console.log("Error, images is undefined");
    return null;
  }
  return this.images[this.image];
}
于 2010-07-05T13:45:11.957 回答