zoukankan      html  css  js  c++  java
  • js深入研究之牛逼的类封装设计

    <script type="text/javascript">
    var Book = function(newIsbn, newTitle, newAuthor) { // implements Publication
    
      // 私有属性
      var isbn, title, author;
    
      // 私有方法
      function checkIsbn(isbn) {
        if(isbn == undefined || typeof isbn != 'string') {
          return false;
        }
        return true; // All tests passed.
      }  
    
      // 特权方法
      this.getIsbn = function() {
        return isbn;
      };
      this.setIsbn = function(newIsbn) {
        if(!checkIsbn(newIsbn)) throw new Error('Book: Invalid ISBN.');
        isbn = newIsbn;
      };
    
      this.getTitle = function() {
        return title;
      };
      this.setTitle = function(newTitle) {
        title = newTitle || 'No title specified';
      };
    
      this.getAuthor = function() {
        return author;
      };
      this.setAuthor = function(newAuthor) {
        author = newAuthor || 'No author specified';
      };
    
      // 构造代码
      this.setIsbn(newIsbn);
      this.setTitle(newTitle);
      this.setAuthor(newAuthor);
    };
    
    // Public, non-privileged methods.
    Book.prototype = {
      display: function() {
        alert("isbn:"+this.getIsbn()+" title:"+this.getTitle()+" author:"+this.getAuthor());
      }
    };
    
    //var theHobbit = new Book(123, '', 'J. R. R. Tolkein'); // 非字符串抛出异常
    var theHobbit = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein'); 
    theHobbit.display(); // Outputs the data by creating and populating an HTML element.
    
    
    </script>

    必须通过get方法来获取数据,因为数据是私有的。

    js设计模式太牛逼了。

  • 相关阅读:
    Android应用基础概念
    Sqlserver Rand
    sqlite3 锁
    上海盛大网络浩方在线招聘网站程序
    代码片段
    泛型类型的返回
    招 .Net 网站程序员, Flash 程序员
    ACS 20070412 TODO
    MSSQL 2005 分页分析及优化
    虚惊一场
  • 原文地址:https://www.cnblogs.com/jiqing9006/p/5048948.html
Copyright © 2011-2022 走看看