How to get a numeric or string value for a javascript object such as a window instead of the string [object]

How to get a numeric or string value for a javascript object such as a window instead of the string [object]

Looking for something like an object identifier, for example 44001 or 0xFF0012, unique to this object

+4
source share
4 answers

Javascript does not support a unique python-like hash for each object. You can create a function to assign a unique string to an object, or get a string if it has already been assigned.

var getUniqueId = (function(){ // uncomment this block if you want to avoid memory leaks // in browsers with crappy garbage collectors. /* try { window.addEventListener('unload', cleanup); window.addEventListener('beforeunload', cleanup); } catch (_) { try { window.attachEvent('onunload', cleanup); window.attachEvent('onbeforeunload', cleanup); } catch (__){}} function cleanup () { guid.knownObjects.length=0; } */ guid.knownObjects=[]; return guid; function guid (obj) { for (var i=guid.knownObjects.length; i--;) { if (guid.knownObjects[i][0]===obj) return guid.knownObjects[i][1]; } var uid='x'+(+(''+Math.random()).substring(2)).toString(32); guid.knownObjects.push([obj, uid]); return uid; } }()); 

Testing:

 getUniqueId(window) > "x7onn8ne58ug" getUniqueId(document) > "x9jeriqjdf9o" getUniqueId(document) > "x9jeriqjdf9o" getUniqueId(window) > "x7onn8ne58ug" 

You can do console.dir (getUniqueId.knownObjects) for some useful debugging information.

 getUniqueId.knownObjects > [ Array 0: DOMWindow 1: "x7onn8ne58ug" , Array 0: HTMLDocument 1: "x9jeriqjdf9o" ] 
+3
source

Javascript does not have built-in support for unique identifiers.

You can change the prototype of an object to include it.

Check this topic: JavaScript object identifier

0
source

What string representation of window do you expect to see?

Objects that provide the toString implementation for the JS runtime are responsible for their value. Therefore, some object, such as HTMLElement , can return, for example, innerHTML for its toString . But it is not, therefore, by default it is a type name.

-1
source

You can write a basic debug file, for example, where you pass your object as o:

 function debug(o){ var r = ''; for (var k in o){ r += k + ' => ' + o[k] + '\n'; } window.alert(r); } 

Or you can search for a dump or print_r eaquivalent, like this one: http://geekswithblogs.net/svanvliet/archive/2006/03/23/simple-javascript-object-dump-function.aspx

-1
source

All Articles