简体   繁体   English

对象属性始终未定义

[英]Object property always undefined

This is the first time I've used JS objects and I'm confused as to why this property is always undefined: 这是我第一次使用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());

The error I get is: 我得到的错误是:

Uncaught TypeError: Cannot read property '0' of undefined 未捕获的TypeError:无法读取未定义的属性“0”

The JSON returned is working fine, and fetch is marked as called in the console (when logged the data is fine as well). 返回的JSON工作正常,并且在控制台中将fetch标记为已调用(登录时数据也很好)。 Why is Rotator.images always undefined? 为什么Rotator.images总是未定义?

Edit: Some console.log results: 编辑:一些console.log结果:

  • Logging data.images in $.getJSON results in correct data. $.getJSON记录data.images $.getJSON得到正确的数据。
  • Logging links in Fetch results in correct data. Fetch记录links得到正确的数据。
  • Logging this.images in Fetch results in correct data. Fetch记录this.images得到正确的数据。
  • Logging this.images in Current results in null. Current记录this.images结果为null。

Because getting JSON is asynchronous, that's why the data is only available in the callback function. 因为获取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

Everything that depends on the data should be placed in the callback function! 所有与数据有关的内容都应放在回调函数中!

You can't use undefined that way. 您不能以这种方式使用undefined Use null instead: 使用null代替:

this.images = null;

and

if (this.images == null) {

Edit: 编辑:

You also have to avoid using the images property if it's null: 您还必须避免使用images属性(如果为null):

Rotator.prototype.Current = function() {
  if (this.images == null) {
    console.log("Error, images is undefined");
    return null;
  }
  return this.images[this.image];
}

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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM