In the previous article, I wrote a tool function $class, and this article will improve it as follows. Implement the following functions
1. Inheritance
2. When a subclass inherits from a parent class, it does not inherit the private attributes of the parent class.
Copy the code code as follows:
/**
* @param {String} className
* @param {String/Function} superCls
* @param {Function} classImp
*/
function $class(className, superCls, classImp){
if(superCls === '') superCls = Object;
functionclazz(){
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]);
}
First write a parent class
Copy the code code as follows:
/**
* Parent class Person
*/
$class('Person','',function(){
//Private attribute age
var age;
this.init = function(n, a){
//Public attribute 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 a subclass, inherit from Person
Copy the code code 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 to school;
};
this.setSchool = function(s){
school = s;
};
});
new a subclass instance
Copy the code code as follows:
var m = new Man('tom', 25, 'pku');
console.log(m.name); // Tom inherits the common attribute name of the parent class and can directly use the dot operator to obtain it.
console.log(m.age); // undefined The private property age of the parent class cannot be obtained directly using the dot operator
console.log(m.getAge()); // 25 The private attribute age can be obtained through the public method getAge of the parent class
console.log(m.school); // undefined Man's own private properties still cannot be obtained through the dot operator
console.log(m.getSchool()); // pku obtains the private attribute school through the getSchool() method