How to implement the private property write class mode of of 2 in JavaScript

  • 2020-03-30 00:45:17
  • OfStack

Last time I wrote a tool function $class, this time I improved the following. Implement the following functions

1, inheritance

2. When subclasses inherit the parent class, they do not inherit the private properties of the parent class


/** 
 * @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]); 
}

So let's write a parent class


$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 that inherit from Person

$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 subclass instance of new

var m = new Man('tom', 25, 'pku'); 
console.log(m.name); //The name of the common property Tom inherits from the parent class can be obtained directly using the point operator
console.log(m.age);  //The private property age of an undefined parent class cannot be obtained directly using the point operator
console.log(m.getAge()); //25 the private property age can be obtained through the parent class's common method, getAge
console.log(m.school); //Undefined Man's own private properties are still not available through the point operator
console.log(m.getSchool()); //Pku gets the private attribute school through the getSchool () method


Related articles: