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