In JavaScript, a function is a class, which is used within a function to set public member variables and methods for a class, for example:
[JavaScript] View plaincopy
- function MyClass (name) {
- var str = "private string"; //private Field
- function Privatefn () { //private method alert (str);
- };
- THIS.name = name;
- THIS.PUBFN = function () {
- Privatefn (); //call Private Method
- Alert ("MYCLASS.PUBFN");
- }
- }
Create an object with new when used:
[JavaScript]View Plaincopy
- var obj = new MyClass ("123");
- var name = Obj.name; //access public Field
- OBJ.PUBFN (); //call Public Method
The above is the most common way of writing JavaScript class, the actual application is less, the most used is written in the form of static class, JavaScript static class has two ways to write:
1. Writing a JSON-like object
[JavaScript]View Plaincopy
- var MyClass = {
- Name: "123",
- PUBFN: function () {
- Alert ("pubfn1 is called");
- }
- };
Call form: Myclass.name, MYCLASS.PUBFN ()
This wording makes the members of the class access public.
2. How anonymous functions are written
[JavaScript]View Plaincopy
- var MyClass = function () {
- var name = "123"; //private Field
- var privatefn = function () { //private method
- alert (name);
- }
- return{ //return public field and method
- Name: "Hello" + name, //public field
- PUBFN: function () {
- Privatefn (); //call Private Method
- Alert ("This is a returned function"); //public Method
- }
- }
- }();
The advantage of this notation is that private and common member methods and variables can be separated, and in practice the complex logic can be written in private methods, and return a common interface calls the private method.
Call form: MyClass. Name, MYCLASS.PUBFN ()
Note the parentheses at the end of the class, which is the function of creating the object and removing the parentheses, then the call form is: MyClass (). Name, MyClass (). PUBFN ().
How JavaScript classes are written