Shane Kenyon
Shane Kenyon

Reputation: 5381

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:

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:

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

Upvotes: 0

Views: 68

Answers (2)

Karan
Karan

Reputation: 12629

You can wrap object before passing it to logger function. And for testLiteral.logMe(); it will log logMe because this inside logMe function will refer to itself.

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);
}

Upvotes: 1

Monica Acha
Monica Acha

Reputation: 1086

var testLiteral = {
  logMe: function() {
    logger(this, 'logMe message');
  }

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

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

Upvotes: 1

Related Questions