1

I have some trouble using the Object properties. I want to evaluate an expression within the myObject context to avoid using the myObject.property.

My final goal is to evaluate a more complex expression like 'property1+property2' instead of 'myObject.property1+myObject.property2'.

I have tried the call method to change the context but, it doesn't seem to see the Object properties in the passed context(i.e. the Object containing the properties)(see the last line of the code below generating the error).

var myObject = {
      property1: 20,
      property2: 5000
};

print(myObject.property1);            // return 20
print(eval.call(myObject,property1)); // ReferenceError: property1 is not defined

Is there any way to use the Object properties without the usage of this. or myObject. prefix?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Cara
  • 11
  • 2

1 Answers1

1

Well, there's with statement which is deprecated and you probably shouldn't use it too much, but in this case maybe it wouldn't be considered harmful:

with(myObject){
 console.log( property1 );   // 20
 console.log( eval('property1') ); //20
 console.log( eval('property1+property2') ); // 5020
}

http://jsfiddle.net/f7d1b79b/1/

pawel
  • 35,827
  • 7
  • 56
  • 53