The way to write classes in JavaScript has been discussed 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
Copy the code code 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. Instead, the getName method can only be used.
Copy the code code as follows:
var p = new Person('jack',23);
console.log(p.age); // undefined
console.log(p.getAge()); // 23
There is nothing surprising about the above, let’s use a tool function to implement it below.
Copy the code code as follows:
/**
* @param {String} className
* @param {Function} classImp
*/
function $class(className, classImp){
functionclazz(){
if(typeof this.init == "function"){
this.init.apply(this, arguments);
}
}
classImp.call(clazz.prototype);
window[className] = clazz;
}
write a class
Copy the code code as follows:
$class('Person', function(){
// Private properties are defined here
var age = '';
this.init = function(n, a){
//The shared properties are hung on this and initialized.
this.name = n;
// Private property initialization
age = a;
};
this.getName = function(){
return this.name;
};
this.getAge = function(){
return age;
}
});
new an instance object
Copy the code code as follows:
var p = new Person('jack',23);
console.log(p.name); // Common to jack, you can use the dot operator to get it
console.log(p.age); // undefined private cannot be obtained through the dot operator
console.log(p.getAge()); // 23 Private age can only be obtained through the public method getAge