Game Development Reference
In-Depth Information
The key lies in the wonderful
JSON
data format. Modern browsers have the very
handy
JSON
object available in the global scope, where we can access two important
functions, namely
JSON.stringify
and
JSON.parse
. With these two methods,
we can serialize complex data, store that in
localStorage
, then unserialize the
data retrieved from the storage, and continue using it in the application.
// 1. Define some class
var Person = function(name) {
this.name = name;
};
// 2. Add functions to the class
Person.prototype.greet = function(){
return "Hello, " + this.name;
};
// 3. Create an array of objects of that class
var people = new Array();
people.push(new Person("Rodrigo"));
people.push(new Person("Silveira"));
// 4. Stringify the complex array, and store it
away
var json = JSON.stringify(people);
localStorage.setItem("people", json);
// 5. Retrieve that serialized data, and parse
it back into what it was
people =
JSON.parse(localStorage.getItem("people"));
people[0].name == "Rodrigo"; // True
people[0] instanceof Person; // False
people[0].greet(); // TypeError: Object has no
method 'greet'
While this is a nice little trick, you will notice what can be a major limitation:
JSON
stringify
does not serialize functions. Also, if you pay close attention to the way
that JSON.stringify works, you will realize that class instances lose all of their "iden-
tity", and only the hard data is maintained. In other words, after we serialize and
unserialize an instance of
Person
, the result will be a simple object literal with no
constructor or prototype information. Still, given that localStorage was never inten-