In fact, the common class is the object template. To enhance js oo features, we can use a JSON object to describe this object template inspired by the mootoos framework. 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.
Copy codeThe 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