这是我第一次使用 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());
我得到的错误是:
Uncaught TypeError: Cannot read property '0' of undefined
返回的 JSON 工作正常,并且 fetch 在控制台中被标记为已调用(记录时数据也正常)。为什么 Rotator.images 总是未定义?
编辑:一些console.log结果:
- 在
$.getJSON
中记录data.images
会产生正确的数据。 - 在
Fetch
中记录链接
会产生正确的数据。 - 在
Fetch
中记录this.images
会产生正确的数据。 - 在
Current
中记录this.images
会导致 null。
最佳答案
因为获取 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
所有依赖于数据的东西都应该放在回调函数中!
关于javascript - 对象属性始终未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3179923/