Je sais comment analyser une Chaîne JSON et le transformer en un Objet JavaScript. Vous pouvez utiliser la fonction eval() de jQuery.parseJSON().
C'est très bien, mais comment puis-je prendre cet Objet JavaScript et le transformer en un particulier d'Objet JavaScript (c'est à dire avec un certain prototype)?
Par exemple, supposons que vous avez:
function Foo()
{
this.a = 3;
this.b = 2;
this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = jQuery.parseJSON({"a":4, "b": 3});
//Something to convert fooJSON into a Foo Object
//....... (this is what I am missing)
alert(fooJSON.test() ); //Prints 12
Encore une fois, je ne suis pas demandez comment convertir une chaîne JSON dans un générique d'Objet JavaScript. Je veux savoir comment faire pour convertir une chaîne JSON dans un "Foo" de l'Objet. C'est, à mon Objet devriez maintenant avoir une fonction "test" et les propriétés de 'a' et 'b'.
Mise à JOUR Après avoir fait quelques recherches, j'ai pensé à cela...
Object.cast = function cast(rawObj, constructor)
{
var obj = new constructor();
for(var i in rawObj)
obj[i] = rawObj[i];
return obj;
}
var fooJSON = Object.cast({"a":4, "b": 3}, Foo);
Ce travail?