mercredi 15 août 2018

Get Javascript 'type' for literal passed into a function

Given the following code:

var testLiteral = {
  logMe: function() {
    logger(this, 'logMe message');
  }
}
console.log(Object.keys({ testLiteral })[0]);
logger(testLiteral, 'mainline message');
testLiteral.logMe();

function logger(caller, message) {
  console.log(Object.keys({ caller })[0] + ': ' + message);
}

We get these results:

  • "testLiteral"
  • "caller: mainline message"
  • "caller: logMe message"

Is there any way to introspect the passed literal to see the original "object" name, i.e. testLiteral? The results I'd be after would be:

  • "testLiteral"
  • "testLiteral: mainline message"
  • "testLiteral: logMe message"

Note: typeof and object.constructor.name don't do the trick with literals, returning simply object and Object respectively.





Aucun commentaire:

Enregistrer un commentaire