JavaScript definition class and class implementation example detailed _javascript skills

Source: Internet
Author: User
Tags class definition

The examples in this article describe the implementation of JavaScript definition classes and classes. Share to everyone for your reference, specific as follows:

It has been frequently seen in several groups that a function in a class is asked how to call this. The method that is exposed after the definition. Now send a class to realize the essay.

First of all, class, in a class we will have the following characteristics:

1. Public methods
2. Private method
3. Property
4. Private variables
5. destructor

Let's look directly at an example:

/*** definition Class ***/
var class = function () {
  var _self = this;//Reference negative value to a variable
  var _field = "Test field";//private Field
  var Privatemethod = function () {//Private Method
    alert (_self. property); Call Property
  } this
  . property = ' Test property '; Public property This
  . methods = function () {//Public method
    alert (_field);//Call Private field
    Privatemethod ();//Invoke Private Method
  }
}

I've written the notes here, and you'll probably see it all at once. For less to write JS friend, may feel strange why I will define a _self variable, because in JS, this is not for other object language, his parsing process and running process this will change. Here simply say JS in the definition of this, if there is a need I can open more than one.

Definition: This is the object that contains the function to which it is invoked as a method.
Feature: This environment can change as the function is assigned to different objects!

Interested friends can find information on the Internet to understand, to the point, the purpose of the _self here is to open more than one private variable, the reference directly to the class itself.

We've just talked about a destructor, which can be implemented directly in code. It is OK to write the execution code directly at the end of the function.

/*** definition Class ***/
var class = function () {
  var _self = this;//Reference negative value to a variable
  var _field = "Test field";//private Field
  var Privatemethod = function () {//Private Method
    alert (_self. property); Call Property
  } this
  . property = ' Test property '; Public property This
  . methods = 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 character, it does not define the class's keyword class, it does not support inherited extend or colons, nor does it support virtual functions, but JavaScript is a flexible language, Let's take a look at how JavaScript, without the keyword class, implements the class definition and creates objects.

One: Define the class and create an instance object of the class

In JavaScript, we use function to define a class, as follows:

function Shape ()
{
var x=1;
var y=2;
}

You might say, suspect? Isn't this the definition function? Yes, this is the definition function, we define a shape function and initialize x and Y. However, if you look at it from a different perspective, this defines a shape class that has two attributes X and Y, and the initial values are 1 and 2, except that we define the class's keyword as a function rather than class.

Then, we can create the object Ashape of the shape class, as follows:

Copy Code code as follows:
var ashape = new Shape ();

Two: Defining Public and private properties

We've created the Ashape object, but when we try to access its properties, we get an error, as follows:

Copy Code code as follows:
Ashape.x=1;

This indicates 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 shape, such as.

Copy Code code as follows:
ashape.x=2;

OK, we can sum it up according to the above code: use Var to define the private property of the class, and use this to define the public property of the class.

Three: Defining public and private methods

In JavaScript, functions are instances of function classes, and functions are indirectly inherited from object, so a function is also an object, so we can use the assignment method to create a function, of course, we can also assign a function to a property variable of a 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 above code and assign a function to it, and we can call this function through Ashape, which is called a public method in OOP, such as:

Copy Code code as follows:
Ashape.draw ();

If defined with Var, the 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 way, you can't use Ashape.draw to invoke this function.

Three: Constructors

JavaScript does not support OOP, and of course there is no constructor, but we can simulate a constructor on our own, let the object be invoked automatically when it is created, the following code:

function Shape ()
{
var init = function ()
{
//constructor code
};
Init ();
}

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

Four: Constructors with parameters

How do I get a constructor with arguments? In fact, it is very simple to write the arguments passed in to the function's argument list, as

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

That way, we can create objects like this:

Copy Code code as follows:
var ashape = new Shape (0,1);

Five: 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
X=ax;
Y=ay;
};
Init ();
}
shape.count=0;//defines a static property count, which belongs to the class and is not object-owned.
shape.staticmethod=function () {};//defines a static method

With the static properties and methods, we can access it with the class name, 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 method of a 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 private property, directly write variable name can be
Y=ay;
this.gx=ax;//access to the public property, you need to precede the variable name with this.
This.gy=ay;
};
Init ();
}

Seven: This is a matter of note

According to the author's experience, this does not always point to the object itself, primarily because JavaScript is not an OOP language, and functions and classes are defined by function, which can cause minor problems.

This pointer refers to the wrong situation generally on the event processing, we want to have 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, of course, Then call this in the member function, of course, there will be an error.

The solution is that we save this to a private property at the beginning of the definition class, and later we can use this property instead of this. I used this method to use this pointer quite safe, and it is very easy to

Let's revise the code to solve this problem. Look at the code in section six, you'll understand.

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

I hope this article will help you with your JavaScript programming.

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.