我创建了一个类似于这个简化示例的自定义对象。我的实现为 Playlist 提供了更复杂的方法:
function Playlist(id) {
var _songs = [];
if(!id)
id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); });
var playlist = {
id: id,
title: "New Playlist",
clear: function(){
_songs = [];
_save();
},
songCount: function () {
return _songs.length;
},
getSongs: function () {
return _songs;
}
}
return playlist;
}
现在,我有另一个对象 Playlists,它保存了 Playlist 对象:
function playlists(){
var _playlists = null;
var _currentPlaylist = null;
var _save = function () {
localStorage.setItem('playlists', JSON.stringify(_playlists));
};
var _loadPlaylists = function(){
_playlists = localStorage.getItem('playlists');
try {
if (_playlists && _playlists != 'undefined')
_playlists = JSON.parse(_playlists);
}
catch(exception){
console.error(exception);
}
if(!_playlists){
_playlists = new Array();
var defaultPlaylist = new Playlist(null, null);
_playlists.push(defaultPlaylist);
_save();
}
};
var playlists = {
count: function(){
return _playlists.length;
},
getPlaylists: function(){
return _playlists;
},
getCurrentPlaylist: function(){
currentPlaylist = _currentPlaylist;
if(!currentPlaylist){
_loadPlaylists();
currentPlaylist = _playlists[0];
currentPlaylist.selected = true;
}
return currentPlaylist;
},
addPlaylist: function(playlistName){
var playlist = new Playlist(null, playlistName);
_playlists.push(playlist);
_save();
}
}
return playlists;
}
当我使用 JSON.parse 将播放列表对象从 JSON 转换为对象时,我注意到播放列表对象已被剥离其方法。我相信这是因为 JSON.stringify 不知道如何(或者它不知道应该)将对象转换为 JSON。
我想知道对此的正确反应是什么?是否可以将方法标记为可序列化?还是需要更多的工作?