Today a small reflection about the object reflection. I’ll try to be concise.
Object reflection in JavaScript
Reflection of objects is not just a curiosity, but also a tool, which we can meet more often than we think. And it may turn out to be this, what we need when we stuck with some issue.
The reflection mechanism allows us to work with the code in the same way, as with the data.
This means that we can operate on the code as on the data, and create our own structures modifying the standard operation of the language.
Reflection is usually encountered in high-level languages, most often based on a virtual machine. Such techniques are probably well known by developers of languages such as Python or Ruby.
When necessary, also in the JavaScript code we can use the object reflection!
The main thing in this case is an overview of the elements, on which our object is built. And this is what we will do now.
Viewing object components
This is possible through the Object.getOwnPropertyNames method.
Example — Math object:
alert(Object.getOwnPropertyNames(Math));
The result will be similar to following:
[toSource,abs,acos,asin,atan,atan2,ceil,cos,exp,floor,imul,fround,log,max,min,pow,random,
round,sin,sqrt,tan,log10,log2,log1p,expm1,cosh,sinh,tanh,acosh,asinh,atanh,trunc,sign,cbrt,
E,LOG2E,LOG10E,LN2,LN10,PI,SQRT2,SQRT1_2]
With just one line of code we received really valuable information that can be further processed.