I do not think that there is a way to change the type of an object after it is created. Fortunately, you probably don't really need to change the class of your objects — you are likely to be satisfied with providing objects with new methods and other functions. (The only real difference is what happens if you change the class and most people do not change the classes while the code is running.)
I will serve as an example for you. First, I will create a simple object to represent the JSON objects that you have:
var myobj = new Object() myobj.name = "Fred"
Then I will create a class that you would like to assign myobj :
function Speaker() { this.speak = function() { window.alert("Hello, " + this.name); } }
This new Speaker class has some useful features: it can use the speak() method to output useful information:
var s = new Speaker() s.name = "Sally" s.speak()
The execution that gave me the message " Hello, Sally ." Unfortunately, you do not need a NEW object (for example, s ) with this functionality, you want an existing object ( myobj ) to have it. Here's how you do it:
myobj.speak = s.speak
Now that I am doing this:
myobj.speak()
I see the message " Hello, Fred ".
To summarize: create an object that does what you want. Copy all methods (and any helper variables) into the new object. Except for some unusual uses of inheritance, this will cause your new object to behave as it wishes.
mcherm
source share