时间:2021-07-01 10:21:17 帮助过:19人阅读
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("sky", "26", "vece@vip.qq.com");
p.showData();演示代码:
<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("PHP中文网", "4", "admin@php.cn");
p.showData();
</script>更多JavaScript之信息的封装 js对象入门相关文章请关注PHP中文网!