Javascript Reflection

In this video Douglas Crockford talks about the good and bad parts of Javascript. One of the things I really like is the easy support for reflection. Suppose we have this code:

function Person (name, salary) {
    this.name = name;
    this.salary = salary;
}

var person = new Person('Vera', 1500);

How do we know if the Person class “has” a certain property? Well, with reflection of course!

The following code checks if the Person class has the properties ‘name’ and ‘birthdate’. If the properties exist, it’s shows the value. If not, a message:

<!DOCTYPE html>
<html>
<head>
    <title>Javascript Reflection</title>
    <script type="text/javascript">
      //<![CDATA[
        function Person (name, salary) {
            this.name = name;
            this.salary = salary;
        }

        var person = new Person('Vera', 1500);

        var name = person["name"];
        if (name !== undefined) {
          document.writeln("name: " + name);
        }

        document.write("<br />");

        var birthdate = person["birthdate"];
        if (birthdate === undefined) {
          document.writeln("Birthdate is not a property of Person");
        }
      //```>
    </script>
</head>
<body>
</body>
</html>

Which outputs:

name: Vera
Birthdate is not a property of Person`

We can also use reflection to iterate the properties of Person:

<!DOCTYPE html>
<html>
<head>
    <title>Javascript Reflection</title>
    <script type="text/javascript">
      //<![CDATA[
        function Person (name, salary) {
            this.name = name;
            this.salary = salary;
        }

        var person=new Person('Vera', 1500);

        for (i in person) {
          document.writeln(i+"="+person[i]);
        }
      //```>
    </script>
</head>
<body>
</body>
</html>

Which outputs:

name=Vera salary=1500