<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>
javascript 设计模式 读书笔记 封装和信息隐藏
最新推荐文章于 2023-05-03 21:15:14 发布