Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make 'constructor' a valid key in a JS object?

Tags:

javascript

I'm currently making a chat AI that uses markov chains. One of the backend objects is an object that maps a string to any chain that it is a part of, such that:

var words = {}

words['test'] = [ ['this','is','a','test'], ['this','too','tests','things'] ]

Now, I have a problem. 'constructor' is a perfectly valid word, but it appears as though you can't map it as I have described above, as 'constructor' is a property of every object in JS (along with other things, of course). So to my question: is there a way to construct this map?

like image 625
Seiyria Avatar asked Dec 26 '22 14:12

Seiyria


1 Answers

constructor isn't a property of every object. Though by default every object created from literal syntax will have constructor in its prototype chain. This is because those objects inherit from Object.prototype, which does have that property.

One solution is to use objects that have no prototype chain.

var words = Object.create(null);

words['test'] = [ ['this','is','a','test'], ['this','too','tests','things'] ];

Now there will be no inherited properties to confuse things. This won't work in IE8 and lower though.


Another solution is to use .hasOwnProperty() to see if the constructor property is on the object itself or inherited. If inherited, then it's not the one you want.

if (words.hasOwnProperty("constructor"))
    console.log(words.constructor);

If the condition passes, then we know we're not using the inherited property, but rather the object's own property.

like image 54
cookie monster Avatar answered Dec 28 '22 07:12

cookie monster