The package and implementation code of JS class

Source: Internet
Author: User

JS is not an orientation-oriented language and does not provide support for classes, so we can not define classes in the same way as in traditional languages, but we could use JS's closure package mechanism to implement the JS class, we encapsulate a simple shape class.

1. Define JS class
JS is not an orientation-oriented language and does not provide support for classes, so we can not define classes in the same way as in traditional languages, but we could use JS's closure package mechanism to implement the JS class, we encapsulate a simple shape class.

The code is as follows:


function Shapebase () {
This.show = function ()
{
Alert ("Shapebase show");
};
This.init = function () {
Alert ("Shapebase init");
};
}


There are two methods defined in this class: Show and Init, it is important to note that this is used to declare, not Var, because Var is used to define private methods.
In addition, we can also use the prototype property to define the method of shape.

The code is as follows:


Shapebase.prototype.show=function ()
{
Alert ("Shapebase show");
}
Shapebase.prototype.init=function ()
{
Alert ("Shapebase init");
}


The above-mentioned wording looks less intuitive, and we can write all the methods together.

The code is as follows:


shapebase.prototype={
Show:function ()
{
Alert ("Shapebase show");
},
Init:function () {
Alert ("Shapebase init");
}
};


Now, the class is written, let's write a JS to test, to see if the result is the same as we imagined it?

The code is as follows:


function Test (SRC) {
var s=new shapebase ();
S.init ();
S.show ();
}


See, it's called the same way as C #, and the results are what we expected.
So far, we have learned how to create the JS class, but only the instance method, if the implementation and the static method in C # How to do?
In fact, the implementation of JS static method is very simple, see below how to achieve:

The code is as follows:


Static methods
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 do this by copying the member methods in the parent class prototype to the prototype of the subclass.
Like inheritance of classes, JavaScript does not have any mechanism to support abstract classes. But take advantage of the nature of the JavaScript language itself. You can implement your own abstract classes.
First of all, the virtual method in JS, in the traditional language virtual method is to be defined first, and the class containing the virtual method is an abstract class, cannot be instantiated, and in JavaScript, the virtual method can be regarded as not defined in the class method, but has been used through the this pointer.
Unlike the traditional object-oriented approach, the virtual method is not declared, but is used directly, and the class can also be instantiated.
Define the Extend method of the object first, one for the static method and one for the instance method, both of which are used to implement the inherited prototype replication

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 implement an inheritance class Rect, which is implemented in a simple way.

The code is as follows:


function Rect () {
}
Rect.prototype = Shapebase.prototype; Just this one sentence.
Expand the new Approach
Rect.prototype.add=function () {
Alert ("Rect add");
}


This method cannot be used for rewriting, and if the Show method is changed, Shapebase's show will also point to the same function possibly because the prototype assignment simply changes the point to the address.
If the above also defines:
Rect.prototype.show=function () {
Alert ("Rect show");
}
The results of the execution are 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 the inheritance, and implement a OnInit virtual method, modify the Shapebase as follows:

The code is as follows:


shapebase.prototype={
Show:function ()
{
Alert ("Shapebase show");
},
Initialize:function () {
This.oninit ();
}
};


Implements the Rect class inheritance.

The 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");
},
Implementing virtual methods
Oninit:function () {
Alert ("Rect oninit");
}
})


Now our class is written and tested to see:

The 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, see an article on the Internet to create a class with a special object, the code is as follows:

The code is as follows:


//
object property Copy method, many libraries are implemented, such as Prototypejs inside the extend and ext inside the ext.apply
//
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 for creating classes
//
Cc.create = function (superclass, constructor) {
var clazz = (function () {
This.initialize.apply (this, arguments);
});
If there are no parameters, the class is returned directly.
if (Arguments.length = = 0)
return clazz;
If there is no parent class, then constructor should be a pure object, and the direct copy property is returned.
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 the property, which is the implementation key.
Extend (Absobj, constructor (Sprpropty));
The subclass instance accesses the parent class property directly through Obj.superclass.
If you do not want to cause too many references, you can also comment out this sentence, because most of the time is not necessary.
Absobj.superclass = Sprpropty;
//
Clazz.constructor = constructor;
}
return clazz;
}
//
To create an animal class
//
var Animal = Cc.create (null, {
Property
Footprint: '-------= ',
Class initialization method, which is required when the method is automatically called when generating a class with new, see above definition.
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) {
In this you can define some class global static data that each instance of the class shares.
Computes instance classes, including instances of derived classes.
var static_instance_counter = 0;
function Classutilityfunchere () {}
Returns the class-specific properties.
return {
Overriding initialization methods
@override
Initialize:function (options) {
Alert (' Initializing Duke class. ');
Call the parent class to initialize, this method is more concise than the other libraries, regardless of the parent class.
Superclass.initialize.call (this, options);
Do some sub-categories like to do things.
Alert (' Duke Initialize method is called. ');
Read or modify class static properties
static_instance_counter++;
},
Rewrite the Move method to increase the way Duke himself moves.
Move:function () {
This.footprint = this.footprint + ' zzzzzzzz ';
Superclass.move.call (this);
},
Overriding 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. ');
},
Added a new say method that shows the number of Duke class instances that are currently initialized.
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 ();
})();

JS class Package and implementation code (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.