The reflection mechanism refers to the information that the program can acquire itself at run time. For example, an object can know what methods and properties they have at run time. There is a handy syntax in JavaScript to implement reflection, that is, for (...) Statement with the following syntax: Hefeng County Tobacco Monopoly Bureau
Here var p represents a variable declared to store the property (method) name of the object obj, with the object name and property (method) name, you can use the square bracket syntax to invoke the properties of an object (method):
3 |
if ( typeof (obj[p]== "function" ){ |
This statement iterates through all the properties and methods of the Obj object, pops its value when the property is encountered, and executes immediately when the method is encountered. As you can see later, in object-oriented JavaScript programming, the reflection mechanism is a very important technique, which plays a great role in the implementation of class inheritance.
Using reflection to pass style parameters
In AJAX programming, it is often to be able to dynamically change the style of the interface elements, which can be changed by the object's style property, such as to change the background color to red, you can write:
1 |
element.style.backgroundColor= "#ff0000" ; |
The Style object has many properties, and basically the properties that are in the CSS are available in JavaScript. If a function receives a parameter using a style that specifies an interface element, it is clear that one or more of the parameters are not compliant, and the following is an implementation:
1 |
function setStyle(_style){ |
3 |
var element=getElement(); |
In this way, the entire style object is passed directly as a parameter, and a style object may be in the form of:
3 |
backgroundColor: #ff0000, |
The function can then be called as follows: SetStyle (style);
or write directly as: SetStyle ({color: #ffffff, BackgroundColor: #ff0000, borderwidth:2px});
This code does not seem to have any problem, but in fact, when using the parameter _style for Element.style assignment inside the SetStyle function, if the element has already had a certain style, such as once executed: element.style.height= "20px";
The _style does not include the definition of height, so the height style of element is lost, not the original result. To solve this problem, you can use the reflection mechanism to override the SetStyle function:
1 |
function setStyle(_style){ |
3 |
var element=getElement(); |
5 |
element.style[p]=_style[p]; |
The program iterates through each property of the _style, gets the property name, and then uses the square bracket syntax to assign the corresponding property in the Element.style to the value of the corresponding property in _style. Thus, the element changes only the specified style, while the other styles do not change, resulting in the desired result.
Example of a JavaScript reflection use