天天看點

js設計模式=封裝

js封裝案例【1】

<script>
var Book = function(num){
    var num;//類私有變量
    var name;//類私有變量
    function check(){};//類私有方法
    this.checkName = function(){}//特權方法
}
Book.prototype.checkNum=10;//公共屬性
Book.prototype.display=function(){//公共方法
    console.log("this is display");
}
Book.isChinese=true;//類似靜态功能屬性
Book.checkInfo=function(){}//類似靜态功能方法

var b1 = new Book();
b1.display();
</script>      
<script>
var Book =(function(){
    //靜态私有變量
    var bookNum=0;
    //靜态私有方法
    function checkBook(name){
        console.log(name);
    }
    //使用了閉包
    return function(newId,newName,newPrice){
        //私有變量
        var name,price;
        //私有方法
        function checkId(){
            console.log(bookNum);
        }
        //特權方法=和外面互動
        this.getName = function(){
            console.log(this.name);
        }
        this.getPrice= function(){
            console.log(this.price);
        }
        this.setPrice= function(newPrice){
            this.price = newPrice;
        }
        this.setName = function(newName){
            this.name = newName;
        }
        this.copy = function(){}
        this.setName(newName);
        this.setPrice(newPrice);
        bookNum++;
        checkId();
        checkBook(newName);
    }
})();
//靜态屬性和方法
Book.prototype={
    isjsBook:false,
    display:function(){}
};

var book = new Book(1,'jsBook',30);
book.getName();
book.getPrice();
</script>      
<script>
 var Book = (function(){
     //靜态私有變量
     var bookNum=0;
     //靜态私有方法
     function checkBook(name){}
     function book (newId,newName,newPrice){
         //私有變量
         var book,price;
         //私有方法
         function checkId(){}
         //特權方法&屬性
         this.getName = function(){}
         this.getPrice = function(){}
         this.setName = function(){}
         this.setPrice = function(){}
         this.copy=function(){}
         //構造方法和屬性
         this.id = newId;
         this.setName(newName);
         this.setPrice(newPrice);
     }
     //構造原型
     book.prototype={
         isJSBook:true,
         display:function(){console.log()}
     };
     return book;
 })();
 var book = new Book(1,'jsbook',20);
 book.display();
 //備注這樣看來是一個完整的整體
</script>      

繼續閱讀