Introduction to Javascript class definition syntax, Private Members, protected members, and static members

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.