0

How do I print out the name of a Path2D object?

var something= new Path2D() and then follows the code for the drawing.

Then I store the variable test in another variable with an if statement.

if (ctx.isPointInPath(test, event.offsetX, event.offsetY)) {

    something = test ...

console.log(something) will give Path2D {}.

console.log(toString(something)) will give [object undefined].

console.log(JSON.stringify(something)) will give {}.
Stefan
  • 17
  • 4
  • Do you mean that, for `var test = new Path2D()`, you want to `console.log` out the string `test`? That is, you want to turn the name of the variable into a string? Try `console.log(Object.keys({test})[0])` – jla May 19 '23 at 04:37
  • That prints out the variable name. I'll update the question because I'm storing a path2D object in the test variable with an if-statement. – Stefan May 19 '23 at 04:46
  • Does this answer your question? [Serializing an ES6 class object as JSON](https://stackoverflow.com/questions/40201589/serializing-an-es6-class-object-as-json) – tresf May 19 '23 at 05:05
  • I'm using JSON.stringify as my third option, the output is {}. – Stefan May 19 '23 at 05:20

1 Answers1

0

JavaScript does not keep track of variable names like that. That's something you'll need to implement yourself.

When you create a Path2D object with let test = new Path2D(), the Path2D object is created in a block of memory. test does not 'contain' the object, it's merely a pointer to the object's memory address. When you store test to another variable, like let something = test, the only thing being copied to something is the memory address of the object. The storage is one way only - the actual Path2D object has no way of keeping track of what variables hold its memory address. In that sense, the Path2D object itself doesn't have a name. There are only the names of variables that hold its address.

You will have to use an additional variable to keep track of the 'name'.

For example:

let test = new Path2D()
let name = 'test'

...

if (ctx.isPointInPath(test, event.offsetX, event.offsetY)) {
    something = test
    name = 'something'
}

console.log( name )
jla
  • 4,191
  • 3
  • 27
  • 44
  • 1
    It was meant to say, "something = new Path2D". I do have a second variable that stores the information in a string like you suggested, but I was hoping there was a way to store the Path2D. Thanks for confirming. – Stefan May 19 '23 at 07:27