I am receiving some JSON object from the server, and I want to 'typecast' or 'bless' it to an object with already defined methods. Is there any way to set a prototype for a plain JSON object?
function MyClass(someValue) {
this.myProperty = someValue;
}
MyClass.prototype.someMethod = function() { return "Here's " + this.myProperty + "!"};
var json = {myProperty : 'someValue'};
// ??? json.prototype = MyClass doesn't work, of course.
var result = json.someMethod();
How can I do that?
Well, I can suggest to try out these:
By adding the needed functions to ALL Javascript objects (bad practice)
By "extending" JSON with a function:
By "making" the object into a function:
Or you can use a JS framework for that. Or any other method that you can think of :) My examples are easy, they can be extended into anything sophisticated you need.
OK. Here is the answer (which is IE-incompatible):
Thankfully, I don't need no %$@$%# IE in my application.
(When I do, there is another possibility: create a wrapper function in MyClass prototype which copies all properties from JSON to the new object; shallow-copying should be enough).