Reflection in JavaScript

While working with JavaScript you may come across a scenario when you need to reflect type of a particular property. Let us say you have an object Student like following,

image

If you want to find type of students object property like name and marks you can get them as following,

image

Now go ahead and fetch type of calculateGrades.

image

You will get expected output as following,

image

If you slightly modify above code as below you will get undefined as output. We have put braces in finding type of function

image

image

While reflecting getting these two values as output may not be good idea

  1. Function
  2. Undefined

You may want to avoid these values in your code or can use other method hasOwnProperty . You can use this method to find that whether object contains that particular property or not. Following code will alert True since name is property of object Student.

image

Now let us go ahead and pass function name calculateGrades as value to hasOwnProperty. You will find true as output again.

image

Interestingly in above code you see that when we pass constructor as input output is false. Reason behind this is hasOwnProperty method does not look for the method in whole property chain. It will only look for the input parameter in current object. As clearly we see that Student object does not have constructor property of its own hence hasOwnProperty is giving false for this.

Better way of doing reflection in JavaScript could be as follows,

image

By using hasOwnProperty method and typeof operator you can work with reflection in JavaScript. I for your reference code discussed in this post is given below,


<script type="text/javascript" >
 function GetData() {

var Student = {
 name: "DJ",
 marks: 100,
 calculateGrades: function () {
 }
 };
 var typeofmarks = typeof (Student.marks);
 alert(typeofmarks);

alert(Student.hasOwnProperty('constructor'));
 alert(Student.hasOwnProperty('calculateGrades'));

if (Student.hasOwnProperty('name')) {
 var typeofname = typeof (Student.name);
 alert(typeofname);
 }

 }

</script>

I hope you find this post useful. Thanks for reading.

About these ads

3 thoughts on “Reflection in JavaScript

  1. Pingback: Dew Drop – July 1, 2013 (#1,576) | Alvin Ashcraft's Morning Dew

  2. Pingback: Blog Posts of the Week (30th June'13 - 06th July'13) - The South Asia MVP Blog - Site Home - TechNet Blogs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s