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

Autovivification and Javascript - Stack Overflow

programmeradmin0浏览0评论

Does autovivification only have to do with "derefencing" undefined structures, because in JavaScript if you specify a index or a property that doesn't exist won't it dynamically create it? But is this not autovivification because you must declare the underlying structure to first be an object or an array?

Does autovivification only have to do with "derefencing" undefined structures, because in JavaScript if you specify a index or a property that doesn't exist won't it dynamically create it? But is this not autovivification because you must declare the underlying structure to first be an object or an array?

Share Improve this question asked Oct 7, 2011 at 18:29 rubixibucrubixibuc 7,39722 gold badges64 silver badges106 bronze badges 1
  • 1 This is the sort of programming language specific question that belongs on Software Engineering. – zzzzBov Commented Oct 7, 2011 at 18:35
Add a comment  | 

2 Answers 2

Reset to default 14

Namespacing is one area where autovivification might be handy in JavaScript. Currently to "namespace" an object, you have to do this:

var foo = { bar: { baz: {} } };
foo.bar.baz.myValue = 1;

Were autovivification supported by JavaScript, the first line would not be necessary. The ability to add arbitrary properties to objects in JavaScript is due to its being a dynamic language, but is not quite autovivification.

ES6's Proxy can be used for implementing autovivification,

var tree = () => new Proxy({}, { get: (target, name) => name in target ? target[name] : target[name] = tree() });

Test:

var t = tree();
t.bar.baz.myValue = 1;
t.bar.baz.myValue
发布评论

评论列表(0)

  1. 暂无评论