Javascript 扩展对象
What are expando objects in javascripts?
For what purpose we need this ? Any complete example will be appreciated
I found 1 article here Javascript: The red-headed stepchild of web development
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
嗯,在 javascript 中,任何对象都是 Expando 对象。正如本文所述,这意味着每当您尝试访问属性1时,它都会自动创建。
当您为
myProp
分配值时,属性myProp
就会动态创建,即使它以前不存在。在许多其他语言中,例如 C#,这通常是不可能的(实际上 C# 也刚刚启用了 Expando 对象支持,但这不是重点)。要访问 C# 中普通类中的属性,您需要在类中指定它确实具有此属性。1 不太正确。请参阅下面 npup 的评论以获得澄清。
Well, in javascript, any object is an expando object. What it means is, as the article covers, that whenever you try to access a property1 it will automatically be created.
The moment you assign
myProp
a value, the propertymyProp
is dynamically created, eventhough it didn't exist before. In a lot of other languages, such as C#, this is not normally possible (actually C# has just enabled expando object support as well, but that's besides the point). To access a property in a normal class in C#, you need to specify in the class that it does indeed have this property.1 Not quite correct. See npup's comment below for clarification.
除了基本类型(字符串、数字、布尔值)之外的所有类型都是对象并支持 Key:values 结构。可以使用点符号和方括号来访问和设置属性(键)。
Everything except primitive types(string, number,boolean) are objects and support Key:values structure. properties(keys) can be accessed and set using the dot notation as well as the square brackets.
2007 年写的一篇文章使用了 document.all(作为唯一访问元素的方式)?这是一个很大的危险信号。
它只是用一些流行语来装饰“你可以向对象添加属性”。
我们需要能够做到这一点,否则我们将无法存储数据,这将使 JavaScript 成为一种非常无用的语言。
(一切都是数组?不,不是。它在没有 hasOwnProperty 包装器的情况下迭代对象。这不安全。请远离本文,它比无用更糟糕)
An article written in 2007 that uses document.all (as the only way to access elements)? That's a big red flag.
It is just dressing up "You can add properties to an object" with some buzzwords.
We need to be able to do this because otherwise we wouldn't be able to store data, and that would make JavaScript a pretty useless language.
(Everything is an array? No it isn't. And it iterates over an object without a hasOwnProperty wrapper. That isn't safe. Just keep away from the article, it is worse than useless)
JavaScript 将具有特定名称 ID 的元素转换为返回的 DOM 对象的扩展。 此处进行了解释。
JavaScript turns elements with specific IDs of names into expandos of the returned DOM object. It is explained here.