[整理]JavaScriptに静的方法と属性のオブジェクトを作成します.

2070 ワード

/**
   * JavaScript      :
   *          ,               。  :Book
   *          ,               。 。getName、getBookName
   *                 “Arr”   。 :functionArr     
   */
  
  /**   JS     
   *    :       prototype   
   *    :      prototype             (   、    、     、    )。
   *                             
   *    :         
   * 
   * 
   * 
   */
  
  //    ()  :              
  var Book = (function() {
    
    /**
     * Book            ,                      
     */
    // private static attribute
    var numOfBooks = 0;
    // private static method
    function checkIsbn(isbn) {
      if ( isbn === undefined || typeof isbn !== "string") {
        return false;
      }
      
      if ( isbn.length === 0 ) {
        return false;
      }
      
      return true;
    }
    
    //          
    return function( isbn, author, price ) {
      
      var isbn, author, price;
      
      this.setIsbn = function ( isbn ) {
      //if ( !checkIsbn(isbn) ) throw new Error("Boook constructor requires an isbn");
         isbn = isbn;
      }
      this.getIsbn = function () {
        return isbn;
      }
      this.setAuthor = function ( author ) {
        author = author || "";
      }
      this.getAuthor = function () {
        return author;
      }
      this.setPrice = function( price ) {
        price = price || "";
      }
      this.getPrice = function () {
        return price;
      }
      
      numOfBooks++;
      
      this.getNumOfBooks = function() {
        return numOfBooks;
      }
      
      this.setIsbn( isbn );  
      this.setAuthor( author );  
      this.setPrice( price ); 
    }
  })();
  
  // public static method
  Book.convertToTitleCase = function( inputString ) {
    
  }
  
  // public non-privileged methods
  Book.prototype = {
    
    // 
    display : function() {
      alert(this.getIsbn());
    }    
  }
  var book = new Book("a");
  alert(book.getNumOfBooks());
  book = new Book();
  alert(book.getNumOfBooks());