JS設計模式(二)getter setter

使用隱藏類信息的方法實現模擬getset

 

這是完全暴露類信息的代碼

  1. var Book = function(isbn, title, author) {
  2.         if(isbn == undefined) throw new Error('Book constructor requires an isbn.');
  3.         this.isbn = isbn;
  4.         this.title = title || 'No title specified';
  5.         this.author = author || 'No author specified';
  6. }
  7. Book.prototype.display = function() {
  8. ...
  9. };

這是使用 Private Methods Using a Naming Convention 私有方法將信息隱藏

 

  1. var Book = function(isbn, title, author) { // implements Publication
  2. this.setIsbn(isbn);
  3. this.setTitle(title);
  4. this.setAuthor(author);
  5. }
  6. Book.prototype = {
  7. checkIsbn: function(isbn) {
  8. ...
  9. },
  10. getIsbn: function() {
  11. return this._isbn;
  12. },
  13. setIsbn: function(isbn) {
  14. if(!this.checkIsbn(isbn)) throw new Error('Book: Invalid ISBN.');
  15. this._isbn = isbn;
  16. },
  17. getTitle: function() {
  18. return this._title;
  19. },
  20. setTitle: function(title) {
  21. this._title = title || 'No title specified';
  22. },
  23. getAuthor: function() {
  24. return this._author;
  25. },
  26. setAuthor: function(author) {
  27. this._author = author || 'No author specified';
  28. },
  29. display: function() {
  30. ...
  31. }
  32. };

第三種方法 Scope,Nested Functions, and Closures

  1. var Book = function(newIsbn, newTitle, newAuthor) { // implements Publication
  2. // Private attributes.
  3. var isbn, title, author;
  4. // Private method.
  5. function checkIsbn(isbn) { //在方法內定義方法來隱藏
  6. ...
  7. }
  8. // Privileged methods.
  9. this.getIsbn = function() {
  10. return isbn;
  11. };
  12. this.setIsbn = function(newIsbn) {
  13. if(!checkIsbn(newIsbn)) throw new Error('Book: Invalid ISBN.');
  14. isbn = newIsbn;
  15. };
  16. this.getTitle = function() {
  17. return title;
  18. };
  19. this.setTitle = function(newTitle) {
  20. title = newTitle || 'No title specified';
  21. };
  22. this.getAuthor = function() {
  23. return author;
  24. };
  25. this.setAuthor = function(newAuthor) {
  26. author = newAuthor || 'No author specified';
  27. };
  28. // Constructor code.
  29. this.setIsbn(newIsbn);
  30. this.setTitle(newTitle);
  31. this.setAuthor(newAuthor);
  32. };
  33. // Public, non-privileged methods.
  34. Book.prototype = {
  35. display: function() {
  36. ...
  37. }
  38. };

常量 Constants

Class.getUPPER_BOUND();

var Class = (function() {
// Constants (created as private static attributes).
var UPPER_BOUND = 100;
// Privileged static method.
this.getUPPER_BOUND() {
return UPPER_BOUND;
}
...
// Return the constructor.
return function(constructorArgument) {
...
}
})();

 

爲了避免類的完整和獨立,使用上述方法。!!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章