The encapsulation of JavaScript information
Before coding, we need to know some of the following terms;
Encapsulation: To conceal the manifestation and implementation details of internal data;
Private properties and methods: The outside world can only access and interact with its exposed interfaces
Scope: JavaScript, only functions have scopes, properties and methods defined within functions cannot be accessed externally
Privileged method: declaration within a function, the ability to access the internal variables (properties) of the method, compared to memory consumption;
Copy Code code as follows:
function person ()
{
/*
* Declaration of private Data
* Nickname, age, email
*/
Var nickname, age, email;
/*
* methods that require access to private data (privileged methods)
* Generate a new copy of the privileged method for each instance generated
*/
This.setdata = function (Pnickname, PAge, Pemail)
{
Nickname = Pnickname;
age = PAge;
email = pemail
};
This.getdata = function ()
{
return [nickname, age, email];
}
}
/*
* Methods that do not require direct access to private data (public method)
* No matter how many instances are generated, the public method has only one copy in memory
*/
Person.prototype = {
Showdata:function ()
{
Alert ("Personal information:" + this.getdata (). join ());
}
}
External code accesses internal properties through private or public methods
Copy Code code as follows:
var p = new person ();
P.setdata ("Sky", "num", "vece@vip.qq.com");
P.showdata ();
Demo Code:
<script> function Person () {var nickname, age, email; This.setdata = function (Pnickname, PAge, pemail) {nickname = Pnickname; age = PAge; email = pemail}; This.getdata = function () {return [nickname, age, email]; } Person.prototype = {showdata:function () {alert ("Personal information:" + this.getdata (). join ()); } var p = new person (); P.setdata ("cloud-dwelling community", "4", "admin@jb51.net"); P.showdata (); </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]