Sorry if this is a stupid question, this is my first JS project...
I'm trying to deserialize a custom object in JS using JSON. The problem is, JSON.parse() does not return the object as its original type. Since directly casting the returned object to the desired type doesn't seem possible, that leaves me with the 'reviver' option...
Am I missing something here? Wasn't the entire point of JSON to avoid having to write custom methods to serialize and deserialize objects? What's the point of using JSON if I have to write my own method 'revive' my object?
JSON is a format for raw data. It's very primitive. It supports dictionaries (aka. javascript objects, hashes, associative arrays), arrays, strings, numbers, booleans and null. That's it. The reason it doesn't do more is that those primitives are language agnostic, and nearly all programming language have built in tools to handle those types of data.
If you had other notation like "class" then suddenly it becomes very bound to specific languages or codeboases, and lose it's wide and generic applicability.
So think of JSON as simple raw data. JSON is not instance marshalling or complete object serialization. So yes you need to write "revivers" if you intend to serialize JS objects instantiated from constructors.
This is the approach things like backbone.js take:
new Book({
title: "One Thousand and One Nights",
author: "Scheherazade"
});
You simply pass your plain object of data (the result of your JSON.parse()) to the call to your constructor of choice. From there you can do any number of things to read it's values into your new object.
Javascript has no standard way of Marshalling whole objects like you can in ruby with Marhsal.dump(obj) for instance.
EDIT: One last major point...
Javascript objects don't have a "type" as you would think of it in other languages. A Javascript object is simply a a dictionary of key/value pairs. When you do something like new SomeClass() you get a new object, that has a special prototype property that points to the prototype property of the SomeClass function object. Wether an object is an instance of SomeClass is less of a clear cut question than you may think at first glance.
Instead you may ask "What is my constructor function object?" or "What objects are in my prototype chain?"
So if you wanted to convey "type" in JSON, which is stored as a string, then how would you store a reference to a prototype object? Maybe the prototype object is not named in the global scope at all, and only available via closure? Then when you write that out to string, you have no way of referencing that prototype object anymore at all.
The point is that javascripts prototypical approach to object instantiation, combined with it's closure based lexical scoping and the fact that objects hold their values more like C pointers than literal values, makes it very very hard to fully serialize an object out to a location external to the VM.
Related
I may get hammered for asking something overly vague, so please interpret this as a meta-programming question, as it is meant to be, and not as some sort of indirect flame war.
In trying to understand Javascript's Array a bit deeper, I ran across this W3 reference for Array.valueOf.
It simply says:
The valueOf() method returns the array.
This method is the default method of the array object. Array.valueOf() will return the same as Array
Note: This method will not change the original array.
So, I ask: what's the point? Is there a reason to ever use the Array.valueOf() method? Is it useful in some more complicated constructs, such as when using call or apply? Does it help in piping together functions? Is this simply because it creates a standard method, compared to other objects where the associated valueOf is more useful, and therefore help to generalize Array to other objects?
As far as I can tell, it is exactly identical, so I don't see its value.
This method is inherited from Object.prototype; every object that descends from Object.prototype has it. Primitive wrappers override it to return the corresponding primitive, for example, converting new Number(5) to 5. The default implementation returns the object unchanged.
JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
I was recently reading some tutorials of JavaScript, and every article states that Functions descend from Objects.
The above statements leads to an understanding that Objects were created before Functions were available.
If it is so, then how can constructor of an Object be a function (As per my understanding object Function hasn't been created yet)?
Please help me out with this confusion.
Functions Descend from Objects
In JavaScript functions are basically objects.
They are what is called first class objects - meaning they can do anything that an object can and are basically interchangeable.
Therefore all properties and methods available on the object level are also available on the function level.
You might want to read this
How can constructor of an Object be a function
The short answer is that you are trying to understand something that is irrelevant to understand in order for you to use the Javascript language for coding.
The longer answer is that you must distinguish between built-in objects:
Object
Function
Array
and the objects you create yourself as part of your code.
The built-in objects are part of the Javascript language and are simply available to you out-of-the-box. Your question relates to the internal workings of the language as you are inquiring about how the built-in Object is constructed. This has little value to understand unless you are looking to become part of the team developing the Javascript language.
The objects you create yourself as part of your code is almost always linked to other objects via the objects internal [[Prototype]] property. So if you for example do:
var x = {"foo": "bar"};
you have now created your own object with the property foo and the value bar. You can then do:
console.log(x.hasOwnProperty("foo")); //true
even though x does not have a method called .hasOwnProperty() directly on it. The reason the above code works is, that x is linked to the built-in Object.prototype via x's internal [[Prototype]] property and via this link delegates to Object.prototype.hasOwnProperty(). So all the objects you create as part of your code has access to use the methods on Object.prototype.
Question 1: If there a post such as this one. How would I represent it in JavaScript? I thought was JSO and parse. Other programming language like C++ and JAVA a main function and have map references but where does JavaScript store it's objects?
Question 2: Oh and do I add Event Handlers to each of the HTML representatives elements?
The basic data structure in JavaScript is the object, you would probably use one (or, more likely, a structured collection of them along with more specific data structures such as arrays) to describe the data structure that makes up a webpage.
The main function in Java and C++ is the entry point to the program. In JavaScript, the entry point is the top of the program.
JavaScript stores its objects in memory and references to them in variables and as properties of objects.
You would only add an event handler to an HTML Element object if you wanted to listen for an event on it.
People are saying store objects in variables but it's I was also told its better to hash them and create references to them in an array.
You use the data type most appropriate for the data you are working with.
If you have a:
simple piece of data, use a variable.
collection of ordered data, use an array (or maybe a Set if you are using ES6)
collection of unordered data, use an object (or maybe a Map if you are using ES6)
… and nest to whatever level makes sense.
You might also create a custom data type with a constructor function or (if you are using ES6) a Class.
Among many objects, I need to serialize an instance of a paper.js Point. JSON serialization isn't enough, because it omits all functions, getters/setters, and fails completely on objects with circular references, all of which I need. I can't write custom serialization for every object that I want to serialize, because there are too many, and they all contain too many properties. Is there a way that I can serialize this object, and deserialize it later such that the deserialized copy behaves the same way?
JavaScript creates a bunch of objects in memory. Even "classes" are really just prototype objects in JavaScript.
I want to create a list of all of the objects currently instantiated on a page. I realize this might include JavaScript basic objects like String.prototype and Number.prototype. I think that's great!
Bonus points for also telling me how to query JavaScript's object space more specifically. Perhaps, say, find all objects currently in memory with a property key matching "name".