Class implementation in Javascript

Source: Internet
Author: User
Tags mootools

Connection: http://www.cnitblog.com/CoffeeCat/archive/2008/02/25/40138.html

Javascript itself does not support object-oriented features. It does not have an access control operator and does not define the class keyword. It does not support inherited extend or colons, nor does it support virtual functions, however, Javascript is a flexible language. Let's take a look at how Javascript without a keyword class implements class definition and creates objects.

I. Define a class and create an instance object for the class
In Javascript, we use functions to define classes, as shown below:

Function shape ()
{
VaR x = 1;
Var y = 2;
}

You might say, suspect? Isn't this a definition function? Yes, this is the definition function. We have defined a Shape function and initialized x and y. However, from another perspective, this is to define a Shape class, which has two attributes x and y. The initial values are 1 and 2,, we define that the key word of a class is function rather than class.

Then, we can create the aShape object of the Shape class, as shown below:

VaR ashape = new shape ();

Ii. defining public and private attributes
We have created an aShape object. However, when we try to access its attributes, an error occurs, as shown below:

Ashape. x = 1;

This indicates that the property defined with var is private. We need to use the this keyword to define public attributes.

Function shape ()
{
This. x = 1;
This. Y = 2;
}

In this way, we can access the Shape attributes, for example.

Ashape. x = 2;

Well, we can conclude from the code above that var can be used to define the private attribute of the class, while this can be used to define the public attribute of the class.

3. Define public and private methods

In Javascript, a Function is an instance of the Function class. A Function indirectly inherits from an Object. Therefore, a Function is also an Object. Therefore, we can create a Function by assigning values. Of course, we can also assign a function to an attribute variable of the class. This attribute variable can be called a method because it is a executable function. The Code is as follows:

Function shape ()
{
VaR x = 0;
Var y = 1;
This. Draw = function ()
{
// Print;
};
}

In the above Code, we define a draw and assign a function to it. Below, we can call this function through aShape, which is called a public method in OOP, for example:

Ashape. Draw ();

If var is used, the draw becomes private. in OOP, it is called a private method, as shown in

Function shape ()
{
VaR x = 0;
Var y = 1;
VaR draw = function ()
{
// Print;
};
}

In this way, you cannot use aShape. draw to call this function.

Iii. Constructor
Javascript does not support OOP, and of course there is no constructor. However, we can simulate a constructor by ourselves to make the object automatically called when it is created. The Code is as follows:

Function shape ()
{
VaR init = function ()
{
// Constructor code
};

Init ();
}

At the end of the Shape, we manually call the init function, so when we create a Shape object, init will always be automatically called to simulate our constructor.

Iv. constructors with Parameters
How can a constructor contain parameters? In fact, it is very easy to write the parameters to be passed in to the parameter list of the function, as shown in figure

Function shape (ax, ay)
{
VaR x = 0;
Var y = 0;
VaR init = function ()
{
// Constructor
X = ax;
Y = ay;
};

Init ();
}

In this way, we can create an object as follows:

Var aShape = new Shape (0, 1 );

V. Static attributes and static methods
In Javascript, how do I define static attributes and methods? As shown below

Function Shape (ax, ay)
{
Var x = 0;
Var y = 0;
Var init = function ()
{
// Constructor
X = ax;
Y = ay;
};

Init ();
}
Shape. count = 0; // defines a static attribute count, which belongs to a class rather than an object.
Shape. staticMethod = function () {}; // defines a static method.

With static attributes and methods, we can use the class name to access it, as shown below:

Alert (aShape. count );
AShape. staticMethod ();

Note: static attributes and methods are both public. So far, I have no idea how to make static attributes and Methods private ~

6. Access the Public and Private attributes of this class in the method.

Access your own attributes in the class method. Javascript has different access methods for Public and Private attributes. Please refer to the following code.

Function Shape (ax, ay)
{
VaR x = 0;
Var y = 0;
This. GX = 0;
This. Gy = 0;
VaR init = function ()
{
X = ax; // access the private property and write the variable name directly.
Y = Ay;
This. GX = ax; // you need to add this before the variable name to access public attributes.
This. Gy = Ay;
};

Init ();
}

7. Considerations for this
Based on my experience, this in a class does not always point to our object. The main reason is that Javascript is not an OOP language, and function and class are defined by function, of course it will cause some minor problems.
This pointer indicates an error in event processing. We want a member function of an object to respond to an event. When an event is triggered, the system will call this member function, however, the passed this pointer is no longer our own object. Of course, an error will occur when we call this in the member function.
The solution is to save this to a private attribute at the beginning of the definition class. Later, we can use this attribute to replace this. Using this method is quite safe and worry-free ~
Let's modify the code to solve this problem. Check the code in Part 6 and you will understand it.

Function shape (ax, ay)
{
VaR _ this = This; // save this and use _ this to replace this in the future, so that this will not get dizzy.
VaR x = 0;
Var y = 0;
_ This. gx = 0;
_ This. gy = 0;
Var init = function ()
{
X = ax; // access the private property and write the variable name directly.
Y = ay;
_ This. gx = ax; // before the variable name, add this.
_ This. gy = ay;
};

Init ();
}

We talked about how to define classes in Javascript, create class objects, create public and private attributes and methods, create static attributes and methods, and simulate constructors, and discussed the error-prone this.
As for the implementation of OOP in Javascript, the above is the most practical content. Generally, classes are defined using Javascript, and the above Code is enough to create objects. Of course, you can also use mootools or prototype to define classes and create objects. I have used the mootools framework and I feel very good. It has improved the Javascript class simulation and supports class inheritance. Interested readers can try it. Of course, if you use a framework, you need to include relevant js header files in your webpage. Therefore, I still hope that the reader can create classes without a framework. In this way, code efficiency is high, and you can also see that it is not difficult to create a simple class ~
In the next version of Javascript, we will add support for OOP. At that time, we will see the class keywords, public and private access controllers ~ Extend inheritance. If you are interested in the next generation of Javascript, you may first get started with ActionScript3.0. This is a very advanced scripting language. It is a masterpiece of Adobe's acquisition of Macromedia, just like Javascript, all belong to ECMAScript, but AS3.0 is the implementation of ECMAScript 4th. To learn ActionScript3.0, I would like to recommend the "ActionScript3 "written by Sun Ying. This book is excellent, especially for the object-oriented part. It is particularly easy to understand and has vivid examples, after reading the new version of ECMAScript, I was amazed at it and gave me great motivation to continue to study the idea of OOP programming. Interested readers may wish to read it ~

Related Article

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.