js深入研究之牛逼的类封装设计

时间:2023-06-10 13:03:26
<script type="text/javascript">
var Book = function(newIsbn, newTitle, newAuthor) { // implements Publication // 私有属性
var isbn, title, author; // 私有方法
function checkIsbn(isbn) {
if(isbn == undefined || typeof isbn != 'string') {
return false;
}
return true; // All tests passed.
} // 特权方法
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.setIsbn(newIsbn);
this.setTitle(newTitle);
this.setAuthor(newAuthor);
}; // Public, non-privileged methods.
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(); // Outputs the data by creating and populating an HTML element. </script>

必须通过get方法来获取数据,因为数据是私有的。

js设计模式太牛逼了。