Class implementation in JavaScript (2)

Source: Internet
Author: User
Tags mootools

Avascript itself does not support object-oriented objects. It does not have an access control operator and does not have a class keyword defined. It does not support extend or colons inherited, 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, if you change
From the point of view, this is to define a shape class, which has two attributes X and Y. The initial values are 1 and 2, respectively. However, we define the class keywords as 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
In JavaScript, a function is an instance of the function class, and the function indirectly inherits from the object. Therefore, the function is also an object. Therefore, we can use
You can also assign a function to an attribute variable of the class. This attribute variable can be called a method because it is an 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 (shape. Count );
Shape. 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.

In response to the advice of the netizen moon, add this as an incorrect example.

Function shape ()
{
VaR x = 123;
VaR init = function ()
{
Alert (this. X); // The output will be undefined, not 123 here. Cause: This here belongs to the init function, and the init function does not define the variable X.
};

Init ();
}
VaR shape = new shape ();

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.
Off
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 still
You can use mootools or prototype to define classes and create objects. I have used the mootools framework, and it feels very good. It is more perfect for JavaScript class simulation.
And also supports class inheritance. If you are interested, you can try it. Of course, if the framework is used, you need to include the relevant JS header file in your webpage. Therefore, I still hope that the reader can
In this way, the 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
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
For more information, see actionscript3.0. This is a very advanced scripting language. It is a masterpiece of Adobe's acquisition of Macromedia.
Like JavaScript, all belong to ecmascript, except as3.0 is the implementation of ecmascript version 4th. To learn
Actionscript3.0: I strongly recommend "the path to the actionscript3 Palace" by Sun Ying. This book is definitely well written, especially for the object-oriented part. It is particularly popular.
It is easy to understand and the examples are vivid. After reading this article, I feel very rewarding. While admiring the new version of ecmascript, It also gives me great motivation to continue to learn the idea of OOP programming. Interested readers may wish to try it out.
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.