How to query javascript's object space - javascript

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".

Related

constructor in javascript are also objects?

I've one deep confusion in javascript regarding constructors. Here you go -
objects in javascript are created from the constructors, right?
and constructors are created from the constructor function, right?
and functions in javascript are also objects but functions in javascript are also created from the Function constructor, right?
So to be purely specific is it okay to say constructors in javascript are objects or is it wrong to say like that?
So, in the end, what will you call these, to be pure specific, just constructors or objects?
Math
Number
Array
Object
I've seen on MDN documentation these are listed under pre-built objects. Does that conclude constructors are objects?
Also, it is mentioned everywhere that in javascript everything is an object.
So could anyone please clarify for me if is it okay to say constructors are also objects in javascript?
If it is yes then, HOW DOES A CONSTRUCTOR BECOMES OBJECT (and vice versa) IN JAVASCRIPT, PLEASE THROW SOME LIGHT?

In JavaScript if "Function" descends from "Object", then how was keyword function made available while defining the constructor of object?

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.

Under the hood, are Javascript objects hash tables? [duplicate]

This question already has answers here:
How does JavaScript VM implements Object property access? Is it Hashtable?
(4 answers)
Closed 2 years ago.
I was wondering about how Objects are implemented under the hood in Javascript engines (V8, Spidermonkey, etc). Are they really just Hash Tables? If so, how do they handle collisions?
First of all, the answer is probably somewhat different for different JS engines. Also, I assume you're specifically asking about the property storage; obviously objects have a bunch of other state too (prototype chain link being an obvious one).
In the case of Spidermonkey, objects basically have a linked list of (propname, information about property) pairs, until they have too many properties, when I believe they still keep the linked list (because order matters for properties in JS in practice) but add an out-of-band hashtable that maps property names to entries in the linked list.
There may also be other reasons for the switch to the hashtable; the details haven't exactly been fixed over time and are likely subject to change in the future.
The linked lists and hashtables are actually shared across objects; as long as two objects have the same property names and corresponding property information (which does NOT include the value, for properties with a stored value) and the properties were set in the same order, they're able to share the property linked list.
The actual property values, when those need to be stored, are stored in an array in the object (or more precisely, two arrays; one allocated inline with the object, whose size is fixed at object-creation time, one dynamically allocated and resized as needed for properties that are added later).
Take a look at a similar question How does JavaScript VM implements Object property access? and my answer. Here I described the optimization technique used by JS engines and how it affects the key lookup performance. I hope that knowing of these details let you write more efficient JS code.
One can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table). The keys in this array are the names of the object's properties.
I found this on MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
In JS arrays are associative arrays and objects are also the same.
In JS arrays are basically objects with properties as sequential numbers.

JSON.parse, JS typecasting, and revivers

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.

What is a javascript hash table implementation that avoids object namespace collisions?

First off: I'm using a rather obscure implementation of javascript embedded as a scripting engine for Adobe InDesign CS3. This implementation sometimes diverges from "standard" javascript, hence my problem.
I'm using John Resig's jsdiff library (source here) to compare selections of text between two documents. jsdiff uses vanilla objects as associative arrays to map a word from the text to another object. (See the "ns" and "os" variables in jsdiff.js, around line 129.)
My headaches start when the word "reflect" comes up in the text. "reflect" is a default, read-only property on all objects. When jsdiff tries to assign a value on the associative array to ns['reflect'], everything explodes.
My question: is there a way around this? Is there a way to do a hash table in javascript without using the obvious vanilla object?
Ground rules: switching scripting engines isn't an option. :)
You might be "asking the wrong question" (as Raymond Chen would say); rather than trying to avoid using the vanilla objects, try changing the way the associative array members are named.
The way I'd try to approach this: instead of there being an array member ns["reflect"], change the way that jsdiff builds the arrays so that the member is ns["_reflect"] or some other variation on that.
If the JS implementation you're using supports the hasOwnProperty method for objects, you can use it to test whether a property has explicitly been set for an object or the property is inherited from its prototype. Example:
if(object.hasOwnProperty('testProperty')){
// do something
}
Well given objects in javascript are just associative arrays, there really isn't another built in solution for a hash. You might be able to create your own psuedo hashtable by wrapping a class around some arrays although there will probably be a significant performance hit with the manual work involved.
Just a side note I haven't really used or looked at the jsdiff library so I can't offer any valid insight as per tips or tricks.

Categories