I have discussed writing methods in JavaScript before. Private implementations are not discussed. Read this article.
We know that the implementation of private attributes in JS is essentially var + closure. As follows:
Copy codeThe Code is as follows:
Function Person (n, ){
// Public
This. name = n;
// Private
Var age =;
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 vertex operator. Instead, you can only use the getName method.
Copy codeThe Code is as follows:
Var p = new Person ('jack', 23 );
Console. log (p. age); // undefined
Console. log (p. getAge (); // 23
The above is nothing unusual. Here we use a tool function to implement it.
Copy codeThe Code is as follows:
/**
* @ 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
Copy codeThe Code is as follows:
$ Class ('person ', function (){
// Private attributes are defined here
Var age = '';
This. init = function (n, ){
// Common attributes are mounted on this and initialized
This. name = n;
// Private Attribute Initialization
Age =;
};
This. getName = function (){
Return this. name;
};
This. getAge = function (){
Return age;
}
});
A new instance object
Copy codeThe Code is as follows:
Var p = new Person ('jack', 23 );
Console. log (p. name); // The vertex operator can be used to obtain the data.
Console. log (p. age); // undefined private cannot be obtained through the vertex Operator
Console. log (p. getAge (); // 23 the private age can only be obtained using the common getAge method.