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

  • 2020-03-30 00:40:52
  • OfStack

We discussed how to write classes in JavaScript earlier. Private implementations are not discussed. Check this one out.

We know that the implementation of private properties in JS is essentially var + closure. The following


function Person(n, a){ 
    // public 
    this.name = n; 
    // private 
    var age = a; 
    this.getName = function(){ 
        return this.name; 
    } 
    this.getAge = function(){ 
        return age; 
    } 
} 

As shown in the test, age is private and cannot be obtained with the point operator, but only with the getName method.

var p = new Person('jack',23); 
console.log(p.age);  // undefined 
console.log(p.getAge()); // 23 

This is nothing fancy, but let's do it using a utility function.  


function $class(className, classImp){ 
    function clazz(){ 
        if(typeof this.init == "function"){ 
            this.init.apply(this, arguments); 
        } 
    } 
    classImp.call(clazz.prototype); 
    window[className] = clazz; 
} 

Write a class

$class('Person', function(){ 
    //Private properties are defined here
    var age = ''; 
    this.init = function(n, a){ 
        //The Shared property is hung on this, initialized
        this.name = n; 
        //Private property initialization
        age = a; 
    }; 
    this.getName = function(){ 
        return this.name; 
    }; 
    this.getAge = function(){ 
        return age; 
    } 
}); 

New is an instance object

var p = new Person('jack',23); 
console.log(p.name); //Jack common can be obtained using the point operator
console.log(p.age); //Undefined private cannot be obtained by the point operator
console.log(p.getAge()); //Private age can only be obtained through a Shared method called getAge


Related articles: