1

consider the function:

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

foo();

How to print only the this object's name (window or global....etc), and not it's contents?

vikrant
  • 2,169
  • 1
  • 21
  • 27
  • 3
    in sloppy mode, you can assume that `this` is an object, so `this.constructor.name` should always work. – Patrick Roberts Jul 20 '18 at 14:04
  • Possible duplicate of [How to get the function name from within that function?](https://stackoverflow.com/questions/2648293/how-to-get-the-function-name-from-within-that-function) – Martin Jul 20 '18 at 14:06
  • 1
    no, i am asking for `this` object's name, not the function's name – vikrant Jul 20 '18 at 14:07
  • What's the purpose? – Dave Newton Jul 20 '18 at 14:07
  • There is no reverse mapping in the sense of reference to variable name, plus objects may be anonymous or have multiple "names". – ASDFGerte Jul 20 '18 at 14:09
  • I want to debug a code and i am printing `this` in many places, and using console.log , it is just impossible to distinguish in node.js output in terminal – vikrant Jul 20 '18 at 14:09

3 Answers3

8

You can print an objects name in js with obj.constructor.name.

function foo() {
  console.log(this.constructor.name)
}

foo()

Will print Window

pushkin
  • 9,575
  • 15
  • 51
  • 95
Wamadahama
  • 1,489
  • 13
  • 19
2

You can use this.constructor.name:

function foo() {
  console.log(this.constructor.name);
}

foo();
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
2

by constructor name. console.log(this.constructor.name)

dorintufar
  • 660
  • 9
  • 22