“与”带方括号表示法的范围和属性
是否可以访问在“with”语句内只能使用方括号表示法访问的对象属性。
例子:
var o = { "bad-property": 1, "another:bad:property": 2, "goodProperty": 3 };
with(o) {
console.log(goodProperty); // works awesome
console.log(???) // how to access "bad:property"?
}
Is it possible to access object properties that can only be accessed with the square bracket notation when inside a "with" statement.
Example:
var o = { "bad-property": 1, "another:bad:property": 2, "goodProperty": 3 };
with(o) {
console.log(goodProperty); // works awesome
console.log(???) // how to access "bad:property"?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
哇,这很旧了,但是这里的答案是错误的,实际上有一种方法可以完全按照你的要求去做。
你看到了吗? valueOf() 是一个神奇的词。它返回其父对象的原始值,或者如果该对象没有原始值,则返回对象本身。每个对象和类对象基元都继承此方法,因为它是
Object.prototype
上的内置属性。那么...就这样吧。Wow this is old, but the answers here are wrong, there is in fact way to do exactly as you ask.
Did you see it? valueOf() is the magic word. It returns the primitive value of its parent object, or if the object has no primitive value, the object itself. Every object and object-like primitive inherits this method, as it is a built in property on
Object.prototype
. So...there you go.通常,with 关键字用于解析长命名空间,而不是单个对象引用。我想我需要知道这里使用关键字的意图是什么。我不相信语法解析器会让您摆脱
o.bad:property
的束缚,这基本上就是使用 with 进行编码的内容。如果示例中的 o 对象只是较长名称空间的快捷方式,我的建议是使用 with 在解析中停止一个对象,然后将您的属性放入像这样的字符串中。希望
有帮助。
Generally the with keyword is used to resolve long namespaces, not a single object reference. I guess I'd need to know what the intent of using the keyword here is. I don't believe the syntax parser will let you get away with
o.bad:property
, which is basically what's being coded using with.If the
o
object in the example was just a shortcut to a longer namespace, my recommendation would be to stop one object short in the resolution using with, then put box your property into a string like this...Hope that helps.
据我了解, with(o) 本质上跳转到 o 的范围,因此属性可以通过它们的名称来访问:分别是“bad”和“goodProperty”。
As I understand it with(o) essentially jumps to the scope of o, so properties are accessible by their name: “bad” and “goodProperty” respectively.