Home  >  Article  >  Web Front-end  >  JS class encapsulation and implementation code_js object-oriented

JS class encapsulation and implementation code_js object-oriented

WBOY
WBOYOriginal
2016-05-16 18:40:421025browse
1. Define js classes
JS is not an object-oriented language and does not provide support for classes, so we cannot use classes to define classes like in traditional languages, but we You can use the closure encapsulation mechanism of js to implement js classes. Let’s encapsulate a simple Shape class.
Copy the code 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, please note What's interesting is that this is used to declare here, instead of var, because var is used to define private methods.
In addition, we can also use the prototype attribute to define Shape methods.
Copy code The code is as follows:

ShapeBase.prototype.show=function()
{
alert("ShapeBase show ");
}
ShapeBase.prototype.init=function()
{
alert("ShapeBase init");
}

The above The writing method seems unintuitive, we can write all the methods together.
Copy the code The code is as follows:

ShapeBase.prototype={
show:function()
{
alert("ShapeBase show");
},
init:function() {
alert("ShapeBase init");
}
};

Now, the class is written, let us write a js to test it and see if the result is the same as ours Is it the same as imagined?
Copy code The code is as follows:

function test(src){
var s=new ShapeBase();
s.init();
s.show();
}

See, its calling method is the same as C# Exactly the same, and the result is as we expected.
So far, we have learned how to create a js class, but it is only an instance method. What if we implement a static method in C#?
Actually, implementing static methods in js is very simple. See how to implement it below:
Copy the code The code is as follows:

//Static method
ShapeBase.StaticDraw = function()
{
alert("method draw is static");
}

2. Implement JS class abstraction and inheritance
Similarly, the class inheritance mechanism is not supported in js, but we can achieve this by copying the member methods in the parent class prototype to the child class prototype.
Like class inheritance, JavaScript does not have any mechanism to support abstract classes. However, you can implement your own abstract class by taking advantage of the nature of the JavaScript language itself.
First, let’s take a look at the virtual methods in js. In the traditional Virtual methods in the language must be defined first, and the class containing the virtual method is an abstract class and cannot be instantiated. In JavaScript, a virtual method can be regarded as an undefined method in the class, but it has been used through the this pointer.
Different from traditional object-oriented, virtual methods here do not need to be declared but are used directly, and classes can also be instantiated.
First define the extend method of object, one is a static method and the other is For instance methods, these two methods are used to implement inherited prototype copy
Copy code The code is as follows:

Object.extend = function(destination, source) {
for (property in source) {
destination[property] = source[property];
}
return destination;
}
Object.prototype.extend = function(object) {
return Object.extend.apply(this, [this, object]);
}

Next we To implement an inherited class Rect, here we first use a simple method to implement it.
Copy code The code is as follows:

function Rect() {
}
Rect.prototype = ShapeBase.prototype; //Just this sentence will do
//Expand new methods
Rect.prototype.add=function() {
alert("Rect add");
}

This method cannot be used for overriding. If the show method is changed, ShapeBase's show will also point to the same function. This may be because the prototype assignment simply changes the pointing address.
If it is also defined above:
Rect.prototype.show=function() {
alert("Rect show");
}
Then 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 ShapeBase as follows:
Copy code The code is as follows:

ShapeBase.prototype={
show:function()
{
alert("ShapeBase show");
},
initialize:function () {
this.oninit();
}
};

Implements Rect class inheritance.
Copy code The code is as follows:

Rect.prototype=(new ShapeBase).extend({
//Add new method
add:function() {
alert("Rect add");
},
//Use this method to override the show method
show:function() {
alert("Rect show");
},
//Implement virtual method
oninit:function() {
alert("Rect oninit");
}
} )

Now that our class is written, let’s test it:
Copy the code Code 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, I saw an article on the Internet that uses special objects to create classes. The code is as follows:
Copy code The code is as follows:

//
//Object attribute copy method, many libraries have implemented it, 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 variables
//
//create is used to create classes
/ /
CC.create = function(superclass, constructor){
var clazz = (function() {
this.initialize.apply(this, arguments);
});
/ /If there are no parameters, return the class directly.
if(arguments.length == 0)
return clazz;
//If there is no parent class, the constructor should be a pure object at this time, copy the properties directly and return .
if(!superclass){
extend(clazz.prototype, constructor);
return clazz;
}
var absObj = clazz.prototype,
sprPropty = superclass.prototype ;
if(sprPropty){
//Used to access parent class methods
clazz.superclass = sprPropty;
extend(absObj, sprPropty);
//Call the property constructor to create properties , this is the key to implementation.
extend(absObj, constructor(sprPropty));
// The subclass instance directly accesses the parent class properties through obj.superclass,
// If you don’t want to cause too many references, you can also You can comment this sentence out, because most of the time it is unnecessary.
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 using new to generate a class, see 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){
//Here you can define some class global static data, which is shared by each instance of this class These data.
//Calculate instance classes, including derived class instances.
var static_instance_counter = 0;
function classUtilityFuncHere(){ }
//Return class specific attributes.
return {
//Rewrite the initialization method
//@override
initialize : function(options) {
alert('Initializing Duke class..');
//Call the parent class initialization, This method is simpler than other libraries, and it doesn’t matter what the parent class is.
superclass.initialize.call(this, options);
//Do something the subclass likes to do.
alert('Duke initialize method is called.');
//Read or modify class static attributes
static_instance_counter;
},
//Rewrite the move method to increase Duke's own movement Method.
move : function(){
this.footprint = this.footprint 'zzzzzzzz';
superclass.move.call(this);
},
//Rewrite eat Method, please 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();
})();
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn