The previous article has written a tool function $class, this article consummates below. Implement the following features
1, inheriting
2, the private property of the parent class is not inherited when the subclass inherits the parent class
Copy Code code 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
Copy Code code as follows:
/**
* Parent Type Person
*/
$class (' person ', ', ', function () {
Private Property Age
var age;
This.init = function (n, a) {
Public Property name
THIS.name = n;
Private Property Initialization
age = A;
};
This.getname = function () {
return this.name;
};
This.setname = function (name) {
THIS.name = name;
}
This.getage = function () {
return age;
};
This.setage = function (a) {
age = A;
};
});
Write subclasses, inheriting from person
Copy Code code as follows:
$class ("Mans", 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;
};
});
New Subclass Instance
Copy Code code as follows:
var m = new Man (' Tom ', ' Pku ');
Console.log (M.name); Tom inherits the common property name of the parent class by using the dot operator directly to get
Console.log (M.age); Undefined the private property of the parent class age cannot be obtained directly using the dot operator
Console.log (M.getage ()); 25 Private attribute age can be obtained through the common method Getage of the parent class
Console.log (M.school); Undefined man's own private properties are still not available through the dot operator
Console.log (M.getschool ()); PKU gets private properties through the Getschool () method School