简体   繁体   English

带方括号符号的“具有”范围和属性

[英]“with” scope and properties with square bracket notation

Is it possible to access object properties that can only be accessed with the square bracket notation when inside a "with" statement. 当在“ with”语句中时,是否可以访问只能用方括号表示法访问的对象属性。

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"?
}

Wow this is old, but the answers here are wrong, there is in fact way to do exactly as you ask. 哇,这很古老,但是这里的答案是错误的,实际上有完全按照您要求的方法来做。

with({'!@#$%': 'omg', d: 'hai'}) {
  console.log(d); //hai - naturally
  console.log(valueOf()['!@#$%']); //omg - OMG
}

Did you see it? 你看见了吗? valueOf() is the magic word. valueOf()是神奇的词。 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 . 每个对象和类对象基元都继承此方法,因为它是Object.prototype的内置属性。 So...there you go. 所以...你去了。

Generally the with keyword is used to resolve long namespaces, not a single object reference. 通常,with关键字用于解析长名称空间,而不是单个对象引用。 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. 我不相信语法解析器会让您摆脱o.bad:property ,这基本上就是使用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... 如果示例中的o对象只是较长名称空间的快捷方式,我的建议是使用with停止分辨率较短的一个对象,然后将您的属性放入这样的字符串中...

var nmSpace = new Object();
nmSpace.o = { "bad:property": 1, "goodProperty": 2 };

with (nmSpace) {
    alert(o['goodProperty']); // works awesome
    alert(o['bad:property']);  // now accesses "bad:property"!
}

Hope that helps. 希望能有所帮助。

As I understand it with(o) essentially jumps to the scope of o, so properties are accessible by their name: “bad” and “goodProperty” respectively. 据我了解,with(o)本质上跳到了o的范围,因此可以通过名称分别访问属性:“ bad”和“ goodProperty”。

with(o) {
  bad="new value";
  goodProperty=22;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM