您的位置:首页 > Web前端 > JavaScript

javascript 设计模式 读书笔记 封装和信息隐藏

2013-12-19 17:28 776 查看
<script type="text/javascript">

/*================================== 对象封装 ===============================
/*《javascript 设计模式》 读书笔记 第三章 “封装和信息隐藏” */
/* 涉及概念:私有属性、方法; 特权属性、方法; 静态属性、方法;*/

/*=======================方式一:门户大开型   start=================*/
var Person = function () {
this.name;
}

Book.prototype  = {

getName:function(){
return this.name;
}

}

/*=======================方式一:门户大开型   end=================*/

/*=======================方式二:用命名规范私有成员   start=================*/
var Person = function () {
this.name = "name";
}

Book.prototype  = {

getAge:function(){
return this._age;//_线表示私有属性
},
setAge:function(age){
this._age = age;
}

}

/*=======================方式二:用命名规范私有成员   end=================*/

/*=======================方式三:闭包 私有属性   start=================*/
var Person = function () {

this.name = "name";
var age = 18;

//private method
function run(){

}

//privileged method
this.getAge = function (){

return age;

}
}

Book.prototype  = {

//prototype 方法通过privileged method访问私有属性
reportAge:function(){
this.getAge();
}

}

/*=======================方式三:闭包 私有属性   end=================*/

/*======================= 一个常用完整类的封装   start=================*/

var Person = (function(){
//private static properties
var NEW_NUM = 0;

//private static method
function getNEW_NUM (){
return NEW_NUM;
}

//construct method
return function(){

//public properties
this.name = "name";

//private properties
var age = 18;

//private method
function run(){

}

//public_privilege method
this.getAge = function(){
return age;
}
}

});

Person.prototype = {
//public_public method
reportAge:function(){
this.getAge();//public_privilege method
}
}

//public static properties
Person.SKIN = "yellow"

//public static method
Person.speakLanguage = function(){

}

/*=======================一个常用完整类的封装   end=================*/
<script type="text/javascript">
//一个常用的私有成员封装

var Person = (function(){
var privateMember = "private";
function privateMethod (){
return privateMember;
}
return {
publicMethod:function(){
privateMethod();
}
}
})();

</script>



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: