Pergunta

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"?
}
Foi útil?

Solução

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. 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.

Outras dicas

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...

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) {
  bad="new value";
  goodProperty=22;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top