Home  >  Article  >  Web Front-end  >  Javascript class definition syntax, introduction to private members, protected members, static members, etc._javascript skills

Javascript class definition syntax, introduction to private members, protected members, static members, etc._javascript skills

WBOY
WBOYOriginal
2016-05-16 17:58:301036browse

In fact, in popular terms, a class is the template of an object. In order to enhance the OO features of JS, 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. Class in the code is a custom function that accepts two parameters. The first parameter is the class name and the second parameter is a JSON for an object. template. In this JSON object, the fields "extend", "initialize", and "static" are some predefined keywords, and their meanings are similar to traditional class-based OO languages. The field accessabe 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 so that the modified members have corresponding access rights.

Copy code The code is as follows:

Class("Person" ,{
// Inherit
extend: Animal,
//Constructor
initialize:function(name,sex){
this.name = name;
this.sex = sex;
Person. count ;
},
//Static members
static:{
count: {
accessabe:"private",
value: ""
}
} ,
//Instance member
age: {//Private attribute member
accessabe:"private",
value:0
},
//Public attribute
name : {
accessabe: "public",
value: ""
},
sex:{
accessabe: "public",
value: ""
},
//Method
sleep: {//Protected method
accessabe:"protected",
value: function(){
}
},
say: { //Public methods
accessabe: "public",
value: function(){
retun (this.age-1)
}
}
});
//Call
var xiaom = new Person("小明","男");
xiaom.age //Private properties cannot be accessed
xiaom.sleep() //Protected methods cannot be accessed
xiaom.say() //Public methods can be accessed
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn