What I want to talk about today is how to write classes and static classes in Javascript. This is my usual method. You can also make it easier, or send comments to communicate with you.
First, let's talk about the class. In a class, we have the following features:
1. Public Method
2. Private Method
3. Attributes
4. Private Variables
5. destructor
Let's look at an example:
Class Example
Copy codeThe Code is as follows:
/*** Define class ***/
Var Class = function (){
Var _ self = this; // reference a negative value to a variable.
Var _ Field = "Test Field"; // Private Field
Var privateMethod = function () {// Private Method
Alert (_ self. Property); // call the Property
}
This. Property = "Test Property"; // public Property
This. Method = function () {// public Method
Alert (_ Field); // call a private Field
PrivateMethod (); // call the private Method
}
}
I have written all the comments here, and you will probably understand them at a glance. For friends who write less JavaScript code, they may wonder why I define a variable named _ self, because in JS, this does not need to be used in other object languages, this will change in the parsing and running processes. Here is a brief introduction to the definition of this in js. If you need this, I can open one more article.
Definition: this is the object to which the function that contains it is called as a method.
Feature: the environment of this can be changed as the function is assigned to different objects!
If you are interested, you can find information on the Internet to find out the correct answer. Here _ self aims to open a private variable and direct it to the class itself.
I also talked about the problem of destructor, which can be implemented directly using code. At the end of the function, write and execute the Code directly.
Code
Copy codeThe Code is as follows:
/*** Define class ***/
Var Class = function (){
Var _ self = this; // reference a negative value to a variable.
Var _ Field = "Test Field"; // Private Field
Var privateMethod = function () {// Private Method
Alert (_ self. Property); // call the Property
}
This. Property = "Test Property"; // public Property
This. Method = function () {// public Method
Alert (_ Field); // call a private Field
PrivateMethod (); // call the private Method
}
/*** Destructor ***/
Var init = function (){
PrivateMethod ();
}
Init ();
}
Using this class, I would like to reference my colleague's sentence "very simple !"
Var c = new Class ();
In this way, OK
The definition of the class is finished, and the static class has to wait until the next time. Because MM asked me to drink tea.
How far a person can go depends on who he is