0

I would like to know whats wrong with following JavaScript code -

<html>
<script type="text/javascript">

var p = eval('new { "Color":"Red"}');

alert(p.Color);
</script>
</html>

It is giving me JavaScript error as -

Message: Object doesn't support this action
Line: 4
Char: 1
Code: 0
Parag Meshram
  • 8,281
  • 10
  • 52
  • 88

2 Answers2

3

There are several problems with the code;

firstly you're telling the script to create something new, but you're not telling it what to create. If you aren't creating a custom object, you are creating an Object object, so you need to tell it that:

var p = eval('new Object()');

Now that you are creating a new Object object, you can configure the Color property:

var p = eval('new Object({"Color":"Red"})');

Here is a working fiddle

But, why are you using eval in the first place? eval is evil!

danwellman
  • 9,068
  • 8
  • 60
  • 88
1

Why eval is not working in this snippet?

Because you cannot use the new operator [MDN] with objects, only with functions.

{"Color":"Red"} is evaluated as object literal and not as function.

If you want to parse JSON, use JSON.parse [MDN]. See also JSON.parse vs. eval().

Or create the object literal directly, if it is static:

var p = {"Color":"Red"};

To make it work with eval (which you should avoid to use anyway), remove new and wrap the literal in parenthesis:

var p = eval('({"Color":"Red"})');

The parenthesis are necessary because otherwise JavaScript would evaluate {"Color":"Red"} as a block and throw an error.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143