Private attributes and methods in javaScript and javascript private attributes

Source: Internet
Author: User

Private attributes and methods in javaScript and javascript private attributes

JavaScript does not have special syntax to indicate private, protected, or public attributes and methods.

Java or other languages are different. The members of all objects in JavaScript are public:
Var myobj = {
Mypop: 1,
GetProp: function (){
Return this. myprop;
}
};
Console. log (myobj. myprop); // 'myprop' is publicly accessible
Console. log (myobj. getProp (); // getProp () is also public and accessible

This is also true when using constructors to create objects, that is, all members are still public.

Function Gadget (){
This. name = 'ipod ';
This. stretch = function (){
Return 'ipad ';
};
}
Var toy = new Gadget ();
Console. log (toy. name); // The name is public.
Console. log (toy. stretch (); // stretch () is public

Although javaScript does not have any special syntax for Private Members, you can use closures to implement such

Function. The constructor creates a closure, and any variables within the closure range are not exposed to the constructor.

Other code. However, these private variables can still be used in public methods; that is, they are defined in constructors and

A method that exposes a part of the returned object to the outside.
For example:
Function Gadget (){

// Private variable
Var name = 'ipod ';
// Public Functions
This. getName = function (){
Return name;
};
}
Var toy = new Gadget ();
// The name is undefined and private
Console. log (toy. name );
// Public method access
Console. log (toy. getName (); // output Ipod

As in the above example, it is easy to implement private in Javascript. All you need to do is to wrap the data that needs to be kept as private attributes in the function and ensure that it is a local variable for the function, which means that the external function cannot access it.

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.