This article describes how to write private attributes in JavaScript. For more information, see $ class. Implement the following functions
1. Inheritance
2. When a subclass inherits the parent class, it does not inherit the private attributes of the parent class.
The Code is as follows:
/**
* @ Param {String} className
* @ Param {String/Function} superCls
* @ Param {Function} classImp
*/
Function $ class (className, superCls, classImp ){
If (superCls = '') superCls = Object;
Function clazz (){
If (typeof this. init = "function "){
This. init. apply (this, arguments );
}
}
Var p = clazz. prototype = new superCls ();
Var _ super = superCls. prototype;
Window [className] = clazz;
ClassImp. apply (p, [_ super]);
}
Write a parent class first
The Code is as follows:
/**
* Parent class Person
*/
$ Class ('person ', '', function (){
// Private Property age
Var age;
This. init = function (n, ){
// Public attribute name
This. name = n;
// Private Attribute Initialization
Age =;
};
This. getName = function (){
Return this. name;
};
This. setName = function (name ){
This. name = name;
}
This. getAge = function (){
Return age;
};
This. setAge = function (){
Age =;
};
});
Write subclass, inherited from Person
The Code is as follows:
$ Class ("Man", Person, function (supr ){
Var school;
This. init = function (n, a, s ){
Supr. init. apply (this, [n, a]);
School = s;
}
This. getSchool = function (){
Return school;
};
This. setSchool = function (s ){
School = s;
};
});
A new subclass instance
The Code is as follows:
Var m = new Man ('Tom ', 25, 'pku ');
Console. log (m. name); // tom inherits the common property name of the parent class and can be obtained directly using the vertex operator.
Console. log (m. age); // The private attribute age of the undefined parent class cannot be obtained directly using the vertex operator.
Console. log (m. getAge (); // 25 you can use the common getAge method of the parent class to obtain the private attribute age.
Console. log (m. school); // undefined Man's own private attributes cannot be obtained through the vertex Operator
Console. log (m. getSchool (); // pku obtains the private attribute school through the getSchool () method.