JS class encapsulation and implementation code _JS object-oriented

Source: Internet
Author: User
Tags extend inheritance instance method
1. Define JS class
JS is not a direction-oriented language, does not provide support for the class, so we can not use the class as in the traditional language to define classes, but we could use JS closure package mechanism to implement the JS class, we have to encapsulate a simple shape class.
Copy Code code 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, and note that this is used here to declare, not Var, because Var is used to define private methods.
In addition, we can use the prototype property to define the shape's method.
Copy Code code as follows:

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

This kind of writing looks less intuitive, and we can write all the methods together.
Copy Code code 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, see if the result is the same as we imagined it?
Copy Code code as follows:

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

See, the way it's called is exactly the same as C #, and the result is what we expected.
So far, we've learned how to create a class of JS, but it's just an instance method, what if it's implemented with static methods in C #?
In fact, the implementation of JS static method is very simple, see below how to achieve:
Copy Code code 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 do this by copying the member methods in the parent class prototype to the prototype of the subclass.
Like the inheritance of a class, JavaScript does not have any mechanism to support abstract classes. But using the nature of the JavaScript language itself. You can implement your own abstract class.
First look at the virtual method in JS, in traditional languages, virtual methods are defined first, and classes containing virtual methods are abstract classes that cannot be instantiated, whereas in JavaScript, virtual methods can be viewed as not defined in the class, but are already used by the this pointer.
Unlike traditional object-oriented objects, virtual methods are used directly without declarations, and classes can be instantiated.
First defines the Extend method of object, one for static methods and one for instance methods, which are used to implement inherited prototype replication
Copy Code code 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 inherited class Rect, which is first implemented in a simple way.
Copy Code code as follows:

function Rect () {
}
Rect.prototype = Shapebase.prototype; That's all you have to say.
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 because the prototype assignment is simply a change of point to the address.
If the above also defines:
Rect.prototype.show=function () {
Alert ("Rect show");
}
The results of the implementation 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 use Object.extend to implement inheritance and implement a OnInit virtual method that modifies shapebase as follows:
Copy Code code as follows:

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

Implements RECT class inheritance.
Copy Code code 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 that our class has been written, let's Test it out:
Copy 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, on the Internet to see a special object to create the class, the code is as follows:
Copy Code code as follows:

//
object property Replication methods, many libraries have implementations, 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 a class
//
Cc.create = function (superclass, constructor) {
var clazz = (function () {
This.initialize.apply (this, arguments);
});
If there are no arguments, return the class directly.
if (arguments.length = 0)
return clazz;
If there is no parent class, then constructor should be a pure object, and the attribute return is copied 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 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;
}
//
Create an Animal class
//
var Animal = Cc.create (null, {
Property
Footprint: '-----= ',
Class initialization method, which is required, is automatically invoked when a class is generated with new, as defined above.
Initialize:function (options) {
Extend (this, options);
Alert (' Animal initialize is called. ');
},
Eat:function () {
Alert (' Animal eat 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 that each instance of the class shares.
Computes an instance class, including a derived class instance.
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 initialization, this method is more concise than the general other library, you can regardless of what the parent class is.
Superclass.initialize.call (this, options);
Do something that a child likes to do.
Alert (' Duke Initialize method is called. ');
Read or modify class static properties
static_instance_counter++;
},
Rewrite the Move method to increase the Duke's own way of moving.
Move:function () {
This.footprint = this.footprint + ' zzzzzzzz ';
Superclass.move.call (this);
},
Rewrite the Eat method, noting that the parent class method is not invoked inside, that is, the parent class eat is overwritten.
Eat:function () {
Alert (' Duke is eating ... ');
},
Add a say method that displays the number of instances of the Duke class 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 ();
})();

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.