这里有一些代码可以将对象设置/设置为本地存储。
这个想法是会有一个名为“高分数”的对象。包含每场比赛的高分。
我收到错误消息 this.appLocalData is undefined
我认为发生这种情况是因为在创建高分对象之前,它不存在,因此无法添加它。我不确定解决这个问题的最佳方法。
这是我的代码http://jsfiddle.net/eL7ge/
var localStorageClass = {
set: function (key, value) {
if (!key || !value) {
return;
}
if (typeof value === "object") {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
},
get: function (key) {
var value = localStorage.getItem(key);
if (!value) {
return;
}
if (value[0] === "{") {
value = JSON.parse(value);
}
return value;
}
};
var TestApp = {
appLocalData: null,
init: function () {
this.appLocalData = localStorageClass.get('appData');
},
setHighScore: function (game, score) {
this.appLocalData.set('highScores', game);
},
getHighScore: function (game) {
this.appLocalData.get(game);
}
};
TestApp.init();
TestApp.setHighScore('game1', 999);
alert(testApp.getHighScore('game1'));
答案 0 :(得分:1)
var localStorageClass = {
set: function (key, value) {
if (!key || !value) {
return;
}
if (typeof value === "object") {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
},
get: function (key) {
var value = localStorage.getItem(key);
if (!value) {
return;
}
if (value[0] === "{") {
value = JSON.parse(value);
}
return value;
}
};
var TestApp = {
appLocalData: null,
init: function () {
this.appLocalData = localStorageClass;
},
setHighScore: function (game, score) {
var hs = this.appLocalData.get('highscore');
if (hs === undefined) {
hs = {};
}
hs[game] = score;
this.appLocalData.set('highscore', hs);
},
getHighScore: function (game) {
var hs = this.appLocalData.get('highscore');
return hs[game];
}
};
TestApp.init();
TestApp.setHighScore('game1', 999);
alert(TestApp.getHighScore('game1'));
<强> Working DEMO 强>