1. Define JS classes
JS is not a object-oriented language and does not provide support for classes. Therefore, we cannot use class to define classes as in traditional languages, however, we can use JS closures to implement JS classes. We can encapsulate a simple shape class.
CopyCode The Code is as follows: function shapebase (){
This. Show = function ()
{
Alert ("shapebase show ");
};
This. init = function (){
Alert ("shapebase init ");
};
}
This class defines two methods: Show and init. It should be noted that this is used for declaration, rather than VaR, because VaR is used to define private methods.
In addition, we can use the prototype attribute to define the shape method.Copy codeThe Code is as follows: shapebase. Prototype. Show = function ()
{
Alert ("shapebase show ");
}
Shapebase. Prototype. init = function ()
{
Alert ("shapebase init ");
}
The preceding method is not intuitive. We can write all the methods together.Copy codeThe Code is as follows: shapebase. Prototype = {
Show: function ()
{
Alert ("shapebase show ");
},
Init: function (){
Alert ("shapebase init ");
}
};
Now, the class is well written. Let's write a JS to test it and see if the result is the same as we thought?Copy codeThe Code is as follows: function test (SRC ){
VaR S = new shapebase ();
S. INIT ();
S. Show ();
}
as you can see, the call method is exactly the same as that of C #, and the result is as expected.
so far, we have learned how to create JS classes, but it is only an instance method. What should we do if we implement static methods in C?
In fact, it is very easy to implement the static method of JS. See the following implementation: copy Code the code is as follows: // static method
shapebase. staticdraw = function ()
{< br> alert ("method draw is static");
}
2. JS class abstraction and inheritance
Similarly, JS does not support class inheritance, but we can achieve this by copying the member methods in the parent class prototype to the prototype of the subclass.
similar to class inheritance, JavaScript does not have any mechanism to support abstract classes. however, the nature of the Javascript language is used. you can implement your own abstract classes.
first, let's take a look at the virtual methods in JS. In traditional languages, virtual methods must be defined first. classes that contain virtual methods are abstract classes and cannot be instantiated, in JavaScript, the virtual method can be regarded as a method not defined in the class, but it has been used through the this pointer.
unlike traditional object-oriented methods, virtual methods are directly used without being declared, and classes can be instantiated.
first, define the extend method of the object. One is a static method and the other is an instance method. These two methods are used to copy the inherited prototype copy Code the code is as follows: object. extend = function (destination, source) {
for (property in source) {
destination [property] = source [property];
}< br> return destination;
}< br> object. prototype. extend = function (object) {
return object. extend. apply (this, [This, object]);
}
Next we will implement an inheritance class rect. Here we will use a simple method to implement it.Copy codeThe Code is as follows: function rect (){
}
Rect. Prototype = shapebase. Prototype; // you can use only this sentence.
// Expand the New Method
Rect. Prototype. Add = function (){
Alert ("rect Add ");
}
This method cannot be used for rewriting. If the show method is changed, the show method of shapebase also points to the same function, probably because the prototype assignment simply changes the pointing address.
If the preceding definition is:
Rect. Prototype. Show = function (){
Alert ("rect show ");
}
The execution result is as follows:
Function Test (){
VaR S = new shapebase ();
S. Show (); // result: rect show
VaR r = new rect ();
R. Show (); // result: rect show
R. Add ();
}
We then use object. Extend to implement inheritance and implement an oninit virtual method. Modify the shapebase as follows:Copy codeThe Code is as follows: shapebase. Prototype = {
Show: function ()
{
Alert ("shapebase show ");
},
Initialize: function (){
This. oninit ();
}
};
Implement rect class inheritance.Copy codeThe Code is as follows: rect. Prototype = (New shapebase). Extend ({
// Add a new method
Add: function (){
Alert ("rect Add ");
},
// Use this method to override the show method.
Show: function (){
Alert ("rect show ");
},
// Implement the virtual Method
Oninit: function (){
Alert ("rect oninit ");
}
})
Now we have written the class. Let's test it:Copy codeThe Code is as follows: function test (SRC ){
Shapebase. staticdraw ();
VaR S = new shapebase ();
S. Show (); // alert ("shapebase show ")
VaR r = new rect ();
R. Show (); // alert ("rect show ")
R. Add ();
R. initialize (); // alert ("rect oninit ")
}
In addition, you can see an article on the Internet that uses specialized objects to create classes. The Code is as follows: Copy code The Code is as follows ://
// Object Property replication method. Many libraries are implemented, such as extend in prototypejs and Ext. Apply in ext.
//
Function extend (DES, Src ){
If (! Des)
Des = {};
If (SRC ){
For (var I in SRC ){
Des [I] = SRC [I];
}
}
Return des;
}
VaR CC ={}; // global variable
//
// Create is used to create a class.
//
Cc. Create = function (superclass, constructor ){
VaR clazz = (function (){
This. Initialize. Apply (this, arguments );
});
// If no parameter exists, the class is directly returned.
If (arguments. Length = 0)
Return clazz;
// If there is no parent class, the constructor should be a pure object and the property will be copied and returned directly.
If (! Superclass ){
Extend (clazz. prototype, constructor );
Return clazz;
}
VaR absobj = clazz. prototype,
Sprpropty = superclass. Prototype;
If (sprpropty ){
// Used to access the parent class Method
Clazz. superclass = sprpropty;
Extend (absobj, sprpropty );
// Call the property constructor to create properties, which is the key to implementation.
Extend (absobj, constructor (sprpropty ));
// The subclass instance directly accesses the attributes of the parent class through obj. superclass,
// If you do not want to cause too many references, you can comment out this sentence because it is unnecessary in most cases.
Absobj. superclass = sprpropty;
//
Clazz. constructor = constructor;
}
Return clazz;
}
//
// Create an animal class
//
VaR animal = cc. Create (null ,{
// Attributes
Footprint: '--= ',
// Class initialization method, required. This method is automatically called when a class is generated using new. For details, refer to the definition above.
Initialize: function (options ){
Extend (this, options );
Alert ('animal initialize method is called .');
},
Eat: function (){
Alert ('animal eat method is called .');
},
Move: function (){
Alert ('I am moving like this' + this. Footprint + '.');
}
});
//
// Create a duke class
//
VaR Duke = cc. Create (animal, function (superclass ){
// Global static data of some classes can be defined here, and each instance of this class shares the data.
// Calculate instance classes, including instances of derived classes.
VaR static_instance_counter = 0;
Function classutilityfunchere (){}
// Return the specific attributes of the class.
Return {
// Override the initialization method
// @ Override
Initialize: function (options ){
Alert ('initializing Duke class ..');
// Call the parent class initialization. This method is more concise than other libraries, regardless of the parent class.
Superclass. Initialize. Call (this, options );
// Do something that child classes like to do.
Alert ('Duke initialize method is called .');
// Read or modify static attributes of a class
Static_instance_counter ++;
},
// Override the move method and add the Duke's own move method.
Move: function (){
This. Footprint = This. Footprint + 'zzzzzzzz ';
Superclass. Move. Call (this );
},
// Override the Eat method. Note that the parent class method is not called, that is, the parent class eat is overwritten.
Eat: function (){
Alert ('Duke is eating ..');
},
// Add a new say method to display the number of currently initialized Duke class instances.
Say: function (){
Alert ('the number of Duke instances is '+ static_instance_counter );
}
};
});
VaR dukechild = cc. Create (Duke, function (superclass ){
Return {
Move: function (){
This. Footprint = This. Footprint + '++ = ';
Superclass. Move. Call (this );
},
Say: function (){
Alert (this. MSG | '');
}
};
});
(Function test (){
VaR animal = new animal ();
Animal. Eat ();
Animal. Move ();
VaR dukea = new Duke ();
Dukea. Eat ();
Dukea. Move ();
Dukea. Say ();
VaR dukeb = new Duke ();
Dukeb. Eat ();
Dukeb. Move ();
Dukeb. Say ();
VaR dukec = new dukechild ({MSG: 'I am a child of Duke .'});
Dukec. Move ();
Dukec. Say ();
})();