How to Write private attributes in JavaScript (1)

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.