Skip to content
Advertisement

JavaScript converting the string “constructor” to [Function: Object]

I’m building a parser for a simple interpreter in JavaScript. I have a preprocessor method that removes specific tokens from an input list of tokens produced by the tokenizer:

JavaScript

Each token is an object like this, with both type and value being strings:

JavaScript

Somewhere in this function, when tokens[i].value == 'constructor', said value is being converted to the actual JS keyword constructor (I would assume) and is showing up in debug as [Function: Object]. The word ‘constructor’ appearing in a token has caused no issues elsewhere in the code where it’s handled and appears normal when console.log‘d directly before this loop, so I’m quite confused. Could someone point me in the direction of an explanation here?

I have added several calls to String() to attempt to force 'constructor' to remain a string, but nothing seems to work.

I would assume that I’ve missed something in my code, but is it possible this is a JS issue?

Advertisement

Answer

The problem here is that symbols is a plain object, so it has a constructor property which exists on the prototype. Reading that property returns a constructor, which is a function:

JavaScript

For a lookup, an object which does not have a prototype can be used. These are created with Object.create(null):

JavaScript

It might be worth considering using a Map instead

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement