0

I have below code trying to display the context from where checkObj() is invoked. For example, I need to see the output as 'a' since checkObj is invoked as a.checkObj(). Currently, only the type of 'this' is displayed i.e., Object{}

function checkObj(){
console.log(this);
}

var a = {checkObj:checkObj};
a.checkObj();
Sami Kh
  • 117
  • 2
  • 14
  • 1
    Objects don't have names; variables do. Objects are not necessarily stored in variables (or just one variable, for that matter). – melpomene May 09 '18 at 06:47
  • If you want to log the variable name, `a`? That won't be possible. – sabithpocker May 09 '18 at 06:47
  • Possible duplicate of [Getting the object variable name in JavaScript](https://stackoverflow.com/questions/42870307/getting-the-object-variable-name-in-javascript) – sabithpocker May 09 '18 at 06:51
  • @melpomene So, the only way to find out where the checkObj() is invoked from is by referring the call-stack through debugger tool in browser? – Sami Kh May 09 '18 at 06:53
  • This is not possibly , But you can set a string representation for this object using `toString` method then this is can be useful.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString – Hyyan Abo Fakher May 09 '18 at 06:53
  • @sabithpocker So, the only way to find out where the checkObj() is invoked from is by referring the call-stack through debugger tool in browser? – Sami Kh May 09 '18 at 06:53
  • 1
    If you already have a reference to what you are checking against, you can do `myObj === this`. If you explain what you are actually trying to do and why, may be there is a different way of doing it. – sabithpocker May 09 '18 at 07:00
  • @sabithpocker There is a function declaration of checkObj() in a messy code, and I'm just trying to figure out where it is invoked from and how? – Sami Kh May 09 '18 at 07:04
  • Your best bet is debugger. – sabithpocker May 09 '18 at 07:52
  • You should just put a debugger; statement inside the code and check if the function is called. There is an another function non standard property .caller.name https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller (never ever use this in production!!) which can be useful only for this nested function calls. – Shyam Babu May 09 '18 at 09:08

0 Answers0