Skip to content Skip to sidebar Skip to footer

Is There A Way To Make 'constructor' A Valid Key In A Js Object?

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 = {} wor

Solution 1:

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.

Post a Comment for "Is There A Way To Make 'constructor' A Valid Key In A Js Object?"