SoFunction
Updated on 2025-04-13

Implementation of Javascript classes and static classes

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 have more convenient things, and you can also post comments to communicate with everyone.
First, let’s talk about the class. In a class we have the following characteristics:
1. Public methods
2. Private method
3. Properties
4. Private variables
5. Destructor
Let's take a look at an example:
Class Example
Copy the codeThe code is as follows:

/***Define class***/
var Class = function(){
var _self = this;//Refer to a variable with a negative value
var _Field = "Test Field"; //Private Field
var privateMethod = function(){ //Private method
alert(_self.Property); //Calling properties
}
= "Test Property"; //Public properties
= function(){ //Public method
alert(_Field); //Calling private fields
privateMethod(); //Calling private methods
}
}

I have written all the comments here, and everyone will probably understand them at a glance. For friends who don't write JS, they may find it strange why I define a variable of _self, because in js, this does not need to be used for other object languages, and this will change during its parsing and running. Here I briefly talk about the definition of this in js. If necessary, I can open an additional article.
Definition: this is the object to which the function containing it belongs when it is called as a method.
Feature: This environment can change as the function is assigned to different objects!
If you are interested, you can find information online to learn about it. Let’s go back to the topic. The purpose of _self here is to open an additional private variable and directly point to the class itself.
I just mentioned a destructor problem, which can be implemented directly in code. It is OK to write the execution code directly at the end of the function.
Code
Copy the codeThe code is as follows:

/***Define class***/
var Class = function(){
var _self = this;//Refer to a variable with a negative value
var _Field = "Test Field"; //Private Field
var privateMethod = function(){ //Private method
alert(_self.Property); //Calling properties
}
= "Test Property"; //Public properties
= function(){ //Public method
alert(_Field); //Calling private fields
privateMethod(); //Calling private methods
}
/***Destructor***/
var init = function(){
privateMethod();
}
init();
}

Using this class, quote my colleague's words "very simple!"
var c = new Class();
That's OK
The definition of the class is finished, a static class, it will take until the next time. Because some MM asked me to have tea
How far a person can go depends on who he walks with