There is a convenient syntax implementation reflection in Javascript, that is, (... in ...) statement. Its syntax is for (var p in OBJ) {}. Here, p represents declaring a variable to store the properties and methods of the OBJ object. With the object, you can traverse attributes or methods as follows:
For (var p in OBJ ){
If (typeof (OBJ [p]) = "function "){
OBJ [p] ();
} Else {
Alert (OBJ [p]);
}
}
This statement traverses all the attributes and methods of the OBJ object. If an attribute is encountered, its value is displayed and the method is executed immediately.
Use the reflection mechanism to pass style parameters:
In Ajax programming, the style of interface elements is often dynamically changed. The style attribute of an object can be changed, for example:
// Change the background color to red.
Element. style. backgroundcolor = "red ";
The style object has many attributes. Basically, all attributes in CSS can be used in Javascript. Now, if a function receives parameters to specify the style of an interface element, we need to design the parameter implementation method. Obviously, one or more parameters cannot meet the requirements. The following is an implementation:
Function setstyle (styleview ){
VaR element = getelement ();
Element. Style = styleview;
}
In this way, the entire style object is passed in as a parameter. The possible form of a style object may be:
VaR style = {
Color: red,
Backgroundcolor: Green,
Borderwidth: 2px
}
In this case, you can directly call the function:
Setstyle (style );
In this method, a problem occurs: If the element has a style, for example, it has been executed after addition:
Element. style. Height = "20px ";
There is no definition of height in styleview, so the height style of the element is lost, not the expected result. To solve this problem, you can use the reflection mechanism to override the setstyle function:
Function setstyle (styleview ){
VaR element = getelement ();
For (var p in styleview ){
Element. Style [p] = style [p];
}
}
In the program, each attribute in the styleview is traversed and assigned to the style object of the element. In this way, the element has an attribute that is not defined in the styleview and is saved, achieving the expected purpose.