5. JavaScript Advanced Private Properties

Source: Internet
Author: User

Learning Java or C + + knows that declaring a private property for an object can be done using the Private keyword, but in JavaScript it is possible to declare a private property, and the answer is yes, and you are equivalent to writing a nonsense O (╯-╰) O.

Before implementing the private properties of JavaScript, take a look at a Baidu interview question:

Implements an object that has a private property that cannot be accessed outside the object, but can be set and accessed through an interface.


If you read the previous article, "JavaScript advanced closures," You can quickly solve the above questions. Yes,JavaScript's private property encapsulation is implemented through closures and local variables.

Look at the following practical examples:

Defines a girl's object, with a public "name" and a Private "secret" attribute,

  function Girl (name,boyfriend) {
        this.name = name;
        var secret = boyfriend;//Private Property
        //interface via Getsecret, read private property
        This.getsecret = function () {
            return secret;
       }
        This.setsecret = function (newsecret) {
             secret = Newsecret;
       }
   }

    var girl = new Girl (' Storm goddess ', ' Wolverine ');
    alert (girl.name+ ' likes ' +girl.getsecret ());//Read

    girl.setsecret (' Laser Man ');// Write
    alert (girl.name+ ' like ' +girl.getsecret ());//Read

This implements the private property encapsulation of the JavaScript object, which can only be read and written through the provided interface.




5. JavaScript Advanced Private Properties

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.