DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> JS匿名函數類生成方式實例分析
JS匿名函數類生成方式實例分析
編輯:關於JavaScript     

本文實例講述了JS匿名函數類生成方式。分享給大家供大家參考,具體如下:

<script type="text/javascript">
var Book = (function() {
 // 私有靜態屬性
 var numOfBooks = 0;
 // 私有靜態方法
 function checkIsbn(isbn) {
  if(isbn == undefined || typeof isbn != 'string') {
   return false;
  }
  return true;
 }
 // 返回構造函數
 return function(newIsbn, newTitle, newAuthor) { // implements Publication
  // 私有屬性
  var isbn, title, author;
  // 特權方法
  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';
  };
  // 控制對象數目,構造函數
  numOfBooks++; // Keep track of how many Books have been instantiated
         // with the private static attribute.
  if(numOfBooks > 5) throw new Error('Book: Only 5 instances of Book can be '
    + 'created.');
  this.setIsbn(newIsbn);
  this.setTitle(newTitle);
  this.setAuthor(newAuthor);
 }
})();
// 公有靜態方法
Book.convertToTitleCase = function(inputString) {
 alert('convertToTitleCase');
};
// 公有非特權方法
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();
//theHobbit.convertToTitleCase(); // Uncaught TypeError: Object #<Object> has no method 'convertToTitleCase'
Book.convertToTitleCase(); // 輸出convertToTitleCase
var theHobbit2 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit2.display();
var theHobbit3 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit3.display();
var theHobbit4 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit4.display();
var theHobbit5 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit5.display();
var theHobbit6 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit6.display(); // Uncaught Error: Book: Only 5 instances of Book can be created.
</script>

這裡已經把js出神入化了,佩服到極致,代碼清晰簡潔,美觀,注釋恰到好處。

更多關於JavaScript相關內容可查看本站專題:《JavaScript常用函數技巧匯總》、《javascript面向對象入門教程》、《JavaScript中json操作技巧總結》、《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》

希望本文所述對大家JavaScript程序設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved