> Articles > Reflection In JavaScript

Reflection In JavaScript

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

What is Reflection in JavaScript?

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. Let's see how reflection in JavaScript is achieved.

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.

Reflection In JavaScript - Getting function object

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.

Reflection In JavaScript - Getting properties information

Reflection In JavaScript - Getting 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.

Reflection In JavaScript - Dynamic Method Invocation

Let's see the implementation of reflection in JavaScript.

Implementation

reflection.js

Reflection In JavaScript - Example Source Code

Output

Reflection In JavaScript - Example 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 Reflection In JavaScript is from his Advanced JavaScript course.