首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

javascript设计模式-封装和信息隐藏(上)

2012-08-17 
javascript设计模式--封装和信息隐藏(下)  今天讲解的内容是高级模式(Advanced Patterns),如何实现静态方

javascript设计模式--封装和信息隐藏(下)

  今天讲解的内容是高级模式(Advanced Patterns),如何实现静态方法和属性,常量还有其他一些知识点。

  1.静态方法和属性

  其实要实现这一功能还是要借助于闭包。在上一讲中的第三种实现方式也使用了闭包,但通过那种实现,内部属性和方法是实例级别的。

var Book = (function() {  // Private static attributes.  var numOfBooks = 0;  // Private static method.  function checkIsbn(isbn) {    ...  }  // Return the constructor.  return function(newIsbn, newTitle, newAuthor) { // implements Publication    // Private attributes.    var isbn, title, author;    // Privileged methods.    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.getNumOfBooks = function(){      return numOfBooks;    };    // Constructor code.    numOfBooks++; // Keep track of how many Books have been instantiated    // with the private static attribute.    if(numOfBooks > 50) throw new Error('Book: Only 50 instances of Book can be '                        + 'created.');    this.setIsbn(newIsbn);    this.setTitle(newTitle);    this.setAuthor(newAuthor);  }})();// Public static method.Book.convertToTitleCase = function(inputString) {  ...};// Public, non-privileged methods.Book.prototype = {  display: function() {    ...  }};

  对匿名函数不了解的同学可以自己去查阅相关资料。其实上面的代码等价于:代码2

var tempBook = function() {  // Private static attributes.  var numOfBooks = 0;  // Private static method.  function checkIsbn(isbn) {    ...  }   // Return the constructor.  return function(newIsbn, newTitle, newAuthor) { // implements Publication    ...  }};var Book = tempBook();// Public static method.Book.convertToTitleCase = function(inputString) {  ...}; // Public, non-privileged methods.Book.prototype = {  display: function() {    ...  }};

  那么如果再执行之前的代码会有什么效果呢:

热点排行