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());

私が得るエラーは次のとおりです。

キャッチされていない TypeError: 未定義のプロパティ '0' を読み取ることができません

返された JSON は正常に機能しており、フェッチはコンソールで呼び出されたものとしてマークされています (ログに記録されたデータも問題ありません)。Rotator.images が常に未定義なのはなぜですか?

編集: console.log の結果:

  • ログインdata.imagesする$.getJSONと正しいデータが得られます。
  • ログインlinksするFetchと正しいデータが得られます。
  • ログインthis.imagesするFetchと正しいデータが得られます。
  • ログインthis.imagesするCurrentと null になります。
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

そんな使い方はできませんundefinednull代わりに使用してください:

this.images = null;

if (this.images == null) {

編集:

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 に答える
0

これは私の首に純粋主義者をもたらしますか、それとも受け入れられますか?

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 に答える