JS is just a language that supports object-oriented programming. Through OO, we can make our code organization more humane. However, unlike traditional programming languages, the base and class have no class concept and no member access modifier. This will cause some limitations to our programming work. In fact, the common class is the object template. In order to enhance JS's OO features, inspired by the mootoos framework, we can use a JSON object to describe the template of this object. In this template, we can simulate Private Members, protected members, and static members.
This is a Class definition syntax simulated in JS. In the code, Class is a custom function that accepts two parameters, the first parameter is the class name, and the second parameter is a JSON template used for an object. In this JSON object, the field "extend", "initialize", and "static" are predefined keywords, which indicate similar meanings to the traditional class-based OO language. The accessabe field is used to describe the accessibility of an object member. The value is ("private", "protected", "public"). These keywords are specially processed in the Class function, grant access permissions to the modified members.
The Code is as follows:
Class ("Person ",{
// Inherit
Extend: Animal,
// Constructor
Initialize: function (name, sex ){
This. name = name;
This. sex = sex;
Person. count ++;
},
// Static member
Static :{
Count :{
Accessabe: "private ",
Value :""
}
},
// Instance Member
Age: {// Private Property Member
Accessabe: "private ",
Value: 0
},
// Public attributes
Name :{
Accessabe: "public ",
Value :""
},
Sex :{
Accessabe: "public ",
Value :""
},
// Method
Sleep: {// protected Method
Accessabe: "protected ",
Value: function (){
}
},
Say: {// public Method
Accessabe: "public ",
Value: function (){
Retun (this. age-1)
}
}
});
// Call
Var xiaom = new Person ("James", "male ");
Xiaom. age // Private Attribute cannot be accessed
Xiaom. sleep () // The protected method cannot be accessed.
Xiaom. say () // public method accessible