您的位置:首页 > Web前端 > JavaScript

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

2015-12-15 17:46 507 查看
<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设计模式太牛逼了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: