使用隐藏类信息的方法实现模拟getset
这是完全暴露类信息的代码
- var Book = function(isbn, title, author) {
- if(isbn == undefined) throw new Error('Book constructor requires an isbn.');
- this.isbn = isbn;
- this.title = title || 'No title specified';
- this.author = author || 'No author specified';
- }
- Book.prototype.display = function() {
- ...
- };
这是使用 Private Methods Using a Naming Convention 私有方法将信息隐藏
- var Book = function(isbn, title, author) { // implements Publication
- this.setIsbn(isbn);
- this.setTitle(title);
- this.setAuthor(author);
- }
- Book.prototype = {
- checkIsbn: function(isbn) {
- ...
- },
- getIsbn: function() {
- return this._isbn;
- },
- setIsbn: function(isbn) {
- if(!this.checkIsbn(isbn)) throw new Error('Book: Invalid ISBN.');
- this._isbn = isbn;
- },
- getTitle: function() {
- return this._title;
- },
- setTitle: function(title) {
- this._title = title || 'No title specified';
- },
- getAuthor: function() {
- return this._author;
- },
- setAuthor: function(author) {
- this._author = author || 'No author specified';
- },
- display: function() {
- ...
- }
- };
第三种方法 Scope,Nested Functions, and Closures
- var Book = function(newIsbn, newTitle, newAuthor) { // implements Publication
- // Private attributes.
- var isbn, title, author;
- // Private method.
- function checkIsbn(isbn) { //在方法内定义方法来隐藏
- ...
- }
- // 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';
- };
- // Constructor code.
- this.setIsbn(newIsbn);
- this.setTitle(newTitle);
- this.setAuthor(newAuthor);
- };
- // Public, non-privileged methods.
- Book.prototype = {
- display: function() {
- ...
- }
- };
常量 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) {
...
}
})();
为了避免类的完整和独立,使用上述方法。!!!!