Search code examples
javascriptjsonmootools

Is it possible to cast Javascript anonymous object to a typed object? How?


I'm looking for a way to cast JavaScript anonymous object to a typed Object, ... Using MooTools library (You may create them manually or using other tools), i defined several type, and then Using signalR (Microsoft library for socket programming, you may use AJAX, or some object or ..., etc) i send object from server to client, and i have access to any part of this object, the object is totally look like my type expect it doesn't contains the prototypes...

Sure i can create new Object from data of last object, but it's overdoing, also cast double memory, also CPU overload, ...

I'm not sure if there is a way, but what I am sure is that, some people like me in this decade, will need it if there is possibility to do this...

So how i can cast my Object, to a defined object?

Also there's a hard part in my case... Which is, my Model it self contains an array, which i fill it with other Model (Entity) instances, ...


Solution

  • You appear to be confused by the fact that serializing a Javascript object to JSON necessarily involves removing all non-serializable members, which includes functions and property configurations.

    Sure i can create new Object from data of last object, but it's overdoing, also cast double memory, also CPU overload, ...

    The server and the client cannot share a single Javascript object, because they are different physical machines. You can have one object in each machine's memory, but you can't have one object that both machines share.

    This is a fundamental limitation of the fact that multiple machines are involved. You simply cannot avoid the need for (de)serialization when transferring data between machines. When you have "plain old objects" the (de)serialization happens to be trivial, but it still has to be done.

    What you can do is make the serialization and deserialization process more painless and robust. One of the things I like about Javascript is that it provides painless (de)serialization to/from JSON out of the box. Making it robust typically means writing schemas to define precisely what structure you expect your serialized JSONs to have. Though there is no single standard way of doing that for JSON (unlike XML), there are plenty of Javascript libraries out there that provide a way to define JSON schemas and (de)serialize objects using those schemas.

    Also there's a hard part in my case... Which is, my Model it self contains an array, which i fill it with other Model (Entity) instances, ...

    A proper schema-based serialization library can easily handle that stuff, provided your schemas include all possible Model/Entity types.