In the past, JavaScript was always a function. I was a little confused when I saw someone using JS object-oriented programming. I have seen my colleagues using a very small base over the past few days. JS and simple implementation of JavaScript object-oriented, and easy implementation of inheritance,
Base. js get address: http://dean.edwards.name/base/Base.js
/**
* Create a class
* You can create a class by calling the extend method in the base class:
*/
VaR animal = base. Extend ({
Name: "", // member variable
// Constructor
Constructor: function (name ){
This. Name = Name;
},
// Method
Eat: function (){
This. Say ("Hello! ");
},
Say: function (Message ){
Alert (this. Name + ":" + message );
}
});
// Usage
New Animal ("Tom"). Eat (); // alert: Tom: Hello!
/**
* Inheritance
* Extend: to call this method, you can use another interface to expand an object.
* Base: if a method is overloaded, you can use the base method to access the overloaded method.
*
* All classes created using this method inherit the extend method, so we can simply create subclasses for the animal class.
*/
VaR cat = animal. Extend ({
Eat: function (food ){
If (Food instanceof mouse ){
This. Base (); // call the method that is overloaded.
} Else {
This. Say ("Yuk! I only eat mice .");
}
}
});
VaR mouse = animal. Extend ();
New cat ('cat'). Eat (new mouse (); // alert: Cat: Hello!
New cat ('cat'). Eat ('test'); // alert: Cat: Yuk! I only eat mice.
/**
* comparison of instance methods and class methods
* if you define a class method called Init (not an instance method ), it is automatically called when the class is created.
* the constructor in the prototype construction phase (derived subclass) will never be called
*/
var shape = base. extend ({
constructor: function (x, y) {
alert (x + y);
}< BR> });
var Circle = shape. extend ({// instance interface
constructor: function (X, Y, radius) {
This. base (x, y);
This. radius = radius;
},
radius: 0,
getcircumference: function () {
return 2 * circle. pI * This. radius;
}< BR >},
{// class interface
Pi: 3.14,
init: function () {// The class method will be called when the class is created
alert (2);
}< BR >});
// alert: first 2 after 3
alert (new circle (18.84, 3 ). getcircumference ();