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.