Home  >  Article  >  Web Front-end  >  How to write classes with private attributes in JavaScript (1)_javascript skills

How to write classes with private attributes in JavaScript (1)_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:10:50960browse

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

Copy the code The code is 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.
Copy code The code is as follows:

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.
Copy code The 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 code The code is as follows:

$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
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn