I have discussed how to write classes in JavaScript before. But private implementations are not discussed. Read this article.
We know that the implementation essence of private properties in JS is var closure. As follows
function Person(n, a){
// public
this.name = n;
// private
var age = a;
this.getName = function(){
return this.name;
}
this.getAge = function(){
return age;
}
}
The test is as follows, age is private and cannot be obtained using the dot operator, and Only the getName method can be used.
var p = new Person('jack',23) ;
console.log(p.age); // undefined
console.log(p.getAge()); // 23
There is nothing strange about the above, we will use it below A tool function to implement.
/**
* @param {String} className
* @param {Function} classImp
*/
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 attributes are defined Here
var age = '';
this.init = function(n, a){
// All properties are hung on this, initialized
this.name = n;
// Private property initialization
age = a;
};
this.getName = function(){
return this.name;
};
this.getAge = function( ){
. >
The code is as follows:
var p = new Person('jack',23);
console.log(p.name); // Jack can share Use the dot operator to get
console.log(p.age); // undefined private cannot be obtained through the dot operator
console.log(p.getAge()); // 23 Private age can only Obtain through the common method getAge