What I want to say today is, how to write classes and static classes in JavaScript, this is my usual method, you can also have more convenient, can also send comments to communicate with you.
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:
class Example
Copy Code code as follows:
/*** Definition Class ***/
var Class = function () {
var _self = this;//references itself to a negative value on a variable
var _field = "Test Field"; Private field
var privatemethod = function () {//Private method
Alert (_self. property); Call Properties
}
This. property = ' Test property '; Public properties
This. method = function () {//Public methods
alert (_field); Calling private fields
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, said back to the point, the purpose of the _self here is to open more than one private variable, directly point 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.
Code
Copy Code code as follows:
/*** Definition Class ***/
var Class = function () {
var _self = this;//references itself to a negative value on a variable
var _field = "Test Field"; Private field
var privatemethod = function () {//Private method
Alert (_self. property); Call Properties
}
This. property = ' Test property '; Public properties
This. method = function () {//Public methods
alert (_field); Calling private fields
Privatemethod (); Invoke Private method
}
/*** destructor ***/
var init = function () {
Privatemethod ();
}
Init ();
}
Use this class, quote my colleague's that sentence "very simple!" ”
var c = new Class ();
That's OK.
The definition of the class is finished, static class, to wait until the next time. Because I have to drink tea mm
How far a man can go depends on who he walks with.