這裏是我的JavaScript代碼:爲什麼這個對象突然不確定?
var Model =
{
get: function(id)
{
return this.data[id];
},
data: {},
init: function()
{
var self = this;
$.getJSON(urlToServer, function(data)
{
$.each(data, function(i, object)
{
self.data[object.id] = object;
console.log(object.id); // output is: 1, then 2, then 3
});
});
}
};
Model.init();
console.log(Model); // output is the initialized object with children objects 1, 2, 3
console.log(Model.get(1)); // output is undefined
正如你可以從控制檯輸出我把在評論中看到,一切工作正常,直到最後一行代碼。我定義了一個模型並使用服務器提供的一些JSON對象對它進行初始化。但突然間,當我嘗試通過get()方法訪問單個子對象時,模型看起來是未定義的。
我只是不明白,請幫助我。
謝謝。
被黑的例子在這裏工作:http://jsfiddle.net/jtbowden/dxFmP/1/ – 2012-04-24 18:36:42