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

来源:互联网 发布:绘画软件手机版 编辑:程序博客网 时间:2024/06/08 06:11
<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>

                                             
0 0
原创粉丝点击