用闭包实现私有成员_Private methods with closures

javascript设计模式中讲到的一种私有成员实现方式,前面有讲到过使用下划线约定的方式实现私有成员变量,而闭包保证在函数中定义的变量只能被当前函数作用域里面的函数所访问,从而保证了变量的私有性。

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() {

}
};