CoursesGalaxy Courses Subscription Knowledge Hub
Knowledge Hub
Design Patterns


Reflection In JavaScript

Reflection provides the capability to inspect itself and dynamically invoke the method.

What is Reflection?

Reflection is the ability of code to inspect itself and modify the behavior. Reflection provides the capability to inspect the object at run time and we can dynamically invoke the method. Capability to do at runtime is very beneficial in lot of scenarios. For example, we get the methods to be executed as messages and we have to invoke the methods at run time. There are lot of tools like debugger, code viewer, class diagram generator etc which may require object information. We have to provide extension in Framework so that it can be used as user want. Javascript provides pretty easy way to do the reflection.

Steps for Getting function Information

Here are the steps for getting function information.
Step 1 - Get the function object.
Step 2 - Get the information by iterating function object.

Getting function object

Here are the different ways for getting function object.
1. We can use function name with new to create object.
2. We can use window object and name of function in string with new to create object.
3. We can also use eval() function to convert the function name in string to code and then we can use new to create object. But eval() is considered unsafe and generally it is avoided.




Getting properties and methods information

We can use function name or window object to get the function object and then we can iterate function object to get properties and methods information.






Dynamic Method Invocation

We can use function name or window object to get function object. Then we can get method name as string in a variable. Then we can use () with function object and method to invoke a method.




Implementation

reflection.js




Output





Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books "C In Depth", "Data Structures Through C In Depth". He has 18+ years experience in industry and worked on architecture and design of multiple products. This article is from his course on Advanced JavaScript.







Yearly Subscription


Advanced JavaScript


Design Patterns Through JavaScript

Explore

Courses

Subscription

Knowledge Hub

Design Patterns

Tech Articles

About Us

Overview

Contact Us

CourseGalaxy

CourseGalaxy is focused on transformation of Engineering graduate to Software Engineer to fill the gap between education and industry and provide the training on specific problems of industry to enhance the skills of Engineers in industry to do their job appropriately.

Learn From Us

2018 CourseGalaxy