包装明星——封装

1、属性和方法封装

<script>
    //创建一个类
    var Book = function(id,bookname,price){
        this.id = id;
        this.bookname = bookname;
        this.price = price;
    }
    //也可以通过在类的原型上添加属性添加属性和方法
    //Book.prototype.display = function(){}
    //或者    但是两者不能混用 容易被覆盖
    Book.prototype = {
        display:function(){
            console.log(this.id+' / '+this.bookname+' / '+this.price);
        }
    }
    //类静态公有属性(对象不能访问)
    Book.isChinese = true;
    Book.restTime = function(){
        console.log('new Time');
    }
    //要使用类
    var book1 = new Book(10,'javascript',50);
    book1.display();
    console.log(book1.isChinese);
    console.log(Book.isChinese);
    //book1.restTime();
    Book.restTime();
  </script>

2、闭包实现

<script>
    var Book = (function(){
        var bookNum = 0;
        function checkBook(name){
            console.log(name);
        }
        function _book(newId,newName,newPrice){
            //私有属性
            var name,price;
            //私有方法
            function checkID(id){}
            //特权属性
            this.getName = function(){
                console.log( newName );
            };
            this.getPrice = function(){
                console.log( newPrice );
            };
            this.setName = function(){};
            this.setPrice = function(){};
            //公有属性
            this.id = newId;
            //公有方法
            this.copy = function(){};
            bookNum++;
            if (bookNum > 100)
            {
                throw new Error('我们仅出版100本书');
            }
            //构造器
            this.setName(name);
            this.setPrice(price);
        }
        _book.prototype = {
            //静态公有属性
            isJSBook:false,
            //静态公有方法
            display:function(){}
        }
        return _book;
    })()
    var b = new Book(11,'JavaScript 设计模式',50);
    b.getName();
  </script>

3、创建对象的安全模式

<script>
    var Book = function(name,title,type){
        //如果用new,则创建该对象
        if (this instanceof Book)
        {
            this.name = name;
            this.title = title;
            this.type = type;
        }else {//如果不是则重新创建对象
            return new Book(name,title,type);
        }
        
    }
    
  </script>
原文地址:https://www.cnblogs.com/jokes/p/9583934.html