5. JavaScript advanced private attributes and javascript private attributes

Source: Internet
Author: User

5. JavaScript advanced private attributes and javascript private attributes

Once I have learned java or C ++, I know that it is possible to declare a private attribute for an object using the private keyword. But in JavaScript, it is certainly possible to declare a private attribute, you have written a piece of nonsense.

Before implementing JavaScript's private attributes, let's take a look at Baidu's interview questions:

Implement an object. The object has a private attribute, which cannot be accessed from outside, but can be set and accessed through interfaces.


If you have read the previous article JavaScript advanced closure, you will soon be able to solve the above interview questions. Yes, JavaScript private property encapsulation is implemented through closures and local variables.

See the following example:

Defines a girl's object, which has public "name" and private "secret" attributes,

Function Girl (name, boyfriend ){
This. name = name;
Var secret = boyfriend; // Private Attribute
// Use getSecret as an interface to read private attributes
This. getSecret = function (){
Return secret;
}
This. setSecret = function (newSecret ){
Secret = newSecret;
}
}

Var girl = new Girl ('goddess of storm ', 'wolverine ');
Alert (girl. name + 'like' + girl. getSecret (); // read

Girl. setSecret ('laser Male'); // write
Alert (girl. name + 'like' + girl. getSecret (); // read

In this way, the private property encapsulation of JavaScript objects can only be performed through the provided interface.




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.