> Articles > Reflection In JavaScript
Reflection in JavaScript provides the capability to inspect itself and dynamically invoke the method.
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.
Here are the steps for getting function information.
Step 1 - Get the function object.
Step 2 - Get the information by iterating 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.
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.
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.
Let's see the implementation of reflection in JavaScript.