Autovivification and Javascript

大憨熊 提交于 2019-11-27 07:00:06

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/7691395/autovivification-and-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!