Javascipt class definition and implementation

Source: Internet
Author: User
Tags class definition

Recently on several groups, it is often seen that a function in a class is asked how to invoke this. The method that is exposed after the definition. An essay on the realization of a class is now issued.
First of all, the class, in a class we will have the following several characteristics:
1. Public methods
2. Private methods
3. Properties
4. Private variables
5. Destructors
Let's look directly at an example:

/*** defines class ***/var classes = function () {    var _self = this;//refers itself to a negative value to a variable on    var _field = "Test field";//private field    var Priva Temethod = function () {//Private Method        alert (_self. property); Call Property    } this    . property = ' Test property '; Public property This    . method = function () {//Public method        alert (_field);//Call Private field        Privatemethod ();//Call Private method    }}

I have written all the notes here, and you will probably see it at one glance. For less JS friends, may find it strange why I define a _self variable, because in JS, this does not use for other object language, his parsing process and the running process of this will change. Here is a brief talk about JS in the definition of this, if necessary I can open more than one article.
Definition: This is the object to which the function that contains it belongs when the method is invoked.
Feature: This environment can be changed as the function is assigned to different objects!
Interested friends can find information on the Internet to understand, say back to the point, here the _self purpose is to open more a private variable, the reference directly to the class itself.
Just a question about a destructor, which can be implemented directly in code. It is OK to write the execution code at the end of the function directly.

/*** defines class ***/var classes = function () {    var _self = this;//refers itself to a negative value to a variable on    var _field = "Test field";//private field    var Priva Temethod = function () {//Private Method        alert (_self. property); Call Property    } this    . property = ' Test property '; Public property This    . method = function () {//Public method        alert (_field);//Call Private field        Privatemethod ();//Call private Method    }    /*** destructor ***/    var init = function () {        privatemethod ();    }    Init ();}

Use this class
var c = new Class ();
C.method (); How to use
That's OK.

JavaScript itself does not support object-oriented, it does not have an access control, it does not define the class's keyword class, it does not support inherited extend or colons, it does not support virtual functions of virtual, but JavaScript is a flexible language, Let's look at how JavaScript without the keyword class implements the class definition and creates the object.

One: Define the class and create an instance object of the class
In JavaScript, we use function to define classes, as follows:

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 define a shape function and initialize x and Y. However, if you look at it in a different way, this is defining a shape class with two attributes X and Y, and the initial values are 1 and 2, except that we define the class's keyword as function rather than class.

We can then create the object Ashape of the shape class, as follows:

var ashape = new Shape ();

Two: Define public and private properties
We have created the Ashape object, but when we try to access its properties, we get an error, as follows:

Ashape.x=1;

This means that the attribute defined with VAR is private. We need to use the This keyword to define public properties

function Shape ()
{
This.x=1;
this.y=2;
}

In this way, we can access the properties of the shape, such as.

ashape.x=2;

Well, we can summarize according to the above code: with Var you can define the private property of the class, and this can define the public property of the class.

III: Define public and private methods

In JavaScript, functions are instances of a function class, and functions are indirectly inherited from object, so the function is also an object, so we can create a function with an assignment, and of course, we can assign a function to a property variable of the class, This property variable can be called a method because it is a function that can be executed. The code is as follows:

function Shape ()
{
var x=0;
var Y=1;
This.draw=function ()
{
Print
};
}

We define a draw in the code above and assign a function to it, and we can call it through Ashape, which is called the public method in OOP, such as:

Ashape.draw ();

If it is defined with Var, then this draw becomes private, and OOP is called a private method, such as

function Shape ()
{
var x=0;
var Y=1;
var draw=function ()
{
Print
};
}
This function cannot be called with Ashape.draw.

Three: Constructors
JavaScript does not support OOP, and of course there are no constructors, but we can simulate a constructor ourselves so that the object is automatically called when it is created, with the following code:

function Shape ()
{
var init = function ()
{
Constructor code
};

Init ();
}

At the end of shape, we call the init function artificially, so when we create a Shape object, init is always called automatically, and we can simulate our constructors.

Four: Constructors with parameters
How do I get the constructor to take arguments? In fact, it is very simple to write the arguments that will be passed in to the function's argument list, as

function Shape (Ax,ay)
{
var x=0;
var y=0;
var init = function ()
{
constructor function
X=ax;
Y=ay;
};

Init ();
}

In this way, we can create objects like this:

var ashape = new Shape (0,1);

V: Static properties and Static methods
How do you define static properties and methods in JavaScript? As shown below

function Shape (Ax,ay)
{
var x=0;
var y=0;
var init = function ()
{
constructor function
X=ax;
Y=ay;
};

Init ();
}
shape.count=0;//defines a static property count, which belongs to the class, not to the object.
Shape.staticmethod=function () {};//defines a static method

With static properties and methods, we can use the class name to access it, as follows

alert (Ashape.count);
Ashape.staticmethod ();
Note: Static properties and methods are public, so far I don't know how to make static properties and methods private.

VI: Accessing the public and private properties of this class in a method

To access your own properties in the methods of the class, JavaScript has different access methods for public and private properties, please look at 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, write the variable name directly
Y=ay;
this.gx=ax;//access to the public property, you need to precede the variable name with this.
This.gy=ay;
};

Init ();
}

Seven: Precautions for this
According to the author's experience, this in the class does not always point to the object itself, mainly because JavaScript is not the OOP language, and functions and classes are defined by function, which of course cause minor problems.
This pointer refers to the wrong situation generally above the event processing, we want to let an object's member function to respond to an event, when the event is triggered, the system will call our member function, but the incoming this pointer is not our own object anymore, of course, Calling this again in the member function will of course make an error.
The workaround is that we save this to a private property at the beginning of the definition class, and later we can use this attribute instead of this. I use this pointer in this method is quite safe, and is very worry ~
Let's modify the code to resolve this issue. Look at the code in part six, you must understand.

function Shape (Ax,ay)
{
var _this=this; Save this and replace this with _this, so you won't get dizzy by this.
var x=0;
var y=0;
_this.gx=0;
_this.gy=0;
var init = function ()
{
x=ax;//access the private property, write the variable name directly
Y=ay;
_this.gx=ax;//access to the public property, you need to precede the variable name with this.
_this.gy=ay;
};

Init ();
}

Javascipt class definition and implementation

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.