Encapsulation of information in JavaScript
Before coding, we need to understand the following terms;
Encapsulation: hiding the representation and implementation details of internal data;
Private properties and methods: the outside world can only use it The public interface allows access and interaction with it
Scope: In JavaScript, only functions have scope, and the properties and methods defined inside the function are inaccessible from the outside
Privileged methods: declared inside the function, they can access the inside of the function The variable (attribute) method consumes more memory;
function Person()
{
/*
* Declare private data
* Nickname, age, email
*/
var nickName, age, email;
/*
* Methods that need to access private data (privileged methods)
* Each instance generated will generate a new copy for the privileged method
*/
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 methods)
* No matter how many instances are generated, public methods only exist in memory One copy
*/
Person.prototype = {
showData: function()
{
alert("Personal information:" this.getData().join());
}
}
External code accesses internal properties through private or public methods
var p = new Person();
p.setData("sky", "26", "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("个人信息:" + this.getData().join());
}
}
var p = new Person();
p.setData("脚本之家", "4", "admin@jb51.net");
p.showData();
</script>