Preserve JS Object Methods Over HTTP via JSON

I had the problem this week of sending Javascript objects over HTTP; although you can easily send objects using JSON, you cannot transmit the object methods. I had intended to build a data structure on the server, send it over to the client where different attributes would be changed, and then send the object back to the server where I had hoped to use the object methods, except the methods did not exist any longer.

An Example

Suppose we have an object that accepts a string variable, and prints it to the console in upper case.

var upper = function( x ) {
    this.x = x
    this.show = function() {
        console.log( this.x.toUpperCase() )
    }
}

If we were to send this as a JSON over HTTP, it would show up only having the this.x attribute, not the this.show() method.

A Solution

One possible solution is to “rehydrate” the object once you get it back on the server side. We can redefine the object using all of the properties we received from client as a JSON, and reacquaint the object with its lost methods. Here is an example,

var upper = function( x ) {
    try {
        var data = JSON.parse( x )
        this.x = data.x
    } catch( err ) {
        this.x = x
    }
    this.show = function() {
        console.log( this.x.toUpperCase() )
    }
}

In this example, if we pass the upper class something that JSON.parse() can parse, then it will parse that input and define this.x, otherwise we can pass the class our normal input. In this manner we can redefine objects that we receive from the client and utilize their methods on the server.

Leave a Reply

Your email address will not be published. Required fields are marked *