Javascript is a function language that is too flexible, and its language mechanism is not provided completely.
The entire object-oriented implementation (without the concepts of classes and inheritance), but with its flexible syntax
However, oop can be implemented to a certain extent.
For example, you can use the following syntax to implement the class Testa:
Testa = function (nvalue ){
This. m_nvalue = nvalue;
This. funca = function (){
Alert ("funca:" + this. m_nvalue );
}
}
Use the testa class as follows:
A = new TESTA (100 );
A. funca ();
On the basis of function language, some special syntaxes are required for implementing OOP inheritance,
In the book professional. Javascript. For. Web. Developers,
It lists multiple inheritance implementation syntaxes, which are the most common on the Internet:
Testb = function (){
This. funcb = function (){
Alert ("funcb ");
}
}
Testb. Prototype = new TESTA (100 );
However, this syntax is not suitable for Class Construction with parameters.
Testb = function (nvalue ){
This. supercontructor = Testa;
This. supercontructor (nvalue );
This. funcb = function (){
Alert ("funcb ");
}
}
The inheritance implementation is complete. How can we implement function overloading?
Testb = function (nvalue ){
This. supercontructor = Testa;
This. supercontructor (nvalue );
This. funcb = function (){
Alert ("funcb ");
}
/* Overload the funca function of the parent class */
This. funca = function (){
Alert ("funca overrided by testb:" + this. m_nvalue );
}
}
If funca is reloaded, you also need to call the function of the parent class (similar to the display call ctesta: funca () in C ++ ()),
You can use the following methods:
Testb = function (nvalue ){
This. supercontructor = Testa;
This. supercontructor (nvalue );
This. funcb = function (){
Alert ("funcb ");
}
/* Overload the funca function of the parent class and call the original implementation function of the parent class in the implementation of the subclass */
This. super_funca = This. funca;
This. funca = function (){
If (this. m_nvalue % 2) = 0 ){
Alert ("funca overrided by testb:" + this. m_nvalue );
}
Else {
This. super_funca ();
}
}
}
In addition to these basic OOP functions, JavaScript, as a dynamic language, also supports the dynamic construction of a class or function:
For (VAR I = 0; I <10; I ++ ){
Eval ("function test_func" + I + "() {alert (" + I + ");}");
}
The code above dynamically constructs 10 functions named test_func0 to test_func9. The function is to display numbers 0 to 9 respectively.
This syntax is much more flexible than the macro or template of C/C ++.
This function is particularly useful in DHTML. For dynamically generated DHTML objects, You can dynamically create their corresponding event functions.
(To be continued ...)