Previously discussed how to write in JavaScript. However, private implementations are not discussed. Look at this article.
We know that the implementation of JS private property is the essence of Var + closure. As follows
Copy 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 follows that age is private and can not be obtained using the dot operator, but only with the GetName method.
Copy Code code as follows:
var p = new Person (' Jack ', 23);
Console.log (P.age); Undefined
Console.log (P.getage ()); 23
The above is not unusual, we use a tool function to implement.
Copy Code code 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 Code code as follows:
$class (' person ', function () {
Private properties are defined in this
var age = ';
This.init = function (n, a) {
Common properties hanging on this, initializing
THIS.name = n;
Private Property Initialization
age = A;
};
This.getname = function () {
return this.name;
};
This.getage = function () {
return age;
}
});
New an Instance Object
Copy Code code as follows:
var p = new Person (' Jack ', 23);
Console.log (P.name); Jack has a common use point operator to get
Console.log (P.age); Undefined private can not get through the dot operator
Console.log (P.getage ()); 23 private age can only be acquired by means of a common method getage