最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there a way to make 'constructor' a valid key in a JS object? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jan 23, 2014 at 22:02 SeiyriaSeiyria 2,1323 gold badges25 silver badges52 bronze badges 2
  • Can't you use a constructor function? – elclanrs Commented Jan 23, 2014 at 22:04
  • @elclanrs I think you missed the point of the question: I just wanted a map; no object functionality was needed. – Seiyria Commented Jan 23, 2014 at 22:57
Add a ment  | 

1 Answer 1

Reset to default 12

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.

发布评论

评论列表(0)

  1. 暂无评论