开发者

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

How do I get a numeric or string value for a javascript object such as window开发者_高级运维 instead of the string [object]

Looking for something like an object id, like 44001 or 0xFF0012 that is unique for that object


Javascript doesn't keep a python-like unique hash for each object. You could create a function to assign a unique string to an object, or retrieve the string if it's 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 it out:

getUniqueId(window)
> "x7onn8ne58ug"

getUniqueId(document)
> "x9jeriqjdf9o"

getUniqueId(document)
> "x9jeriqjdf9o"

getUniqueId(window)
> "x7onn8ne58ug"

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

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


Javascript has no native support for unique identifiers.

You can change the Object prototype to include one.

Check this thread: JavaScript Object Id


What string representation of window would you expect to see?

Objects which provide a toString implementation to the JS runtime are responsible for their own value. So some object like HTMLElement could return, say, the innerHTML for its toString. But it doesn't, so the default is the type name.


You can write a basic debug like this, 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜