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设计模式太牛逼了。
相关文章推荐
- js 禁止|阻止滚动条滚动
- JS之稳妥构造函数模式and静态私有变量
- js深入研究之函数内的函数
- JavaScript中以一个方法作为参数的写法
- JS对table添加删除一行
- JS各种方法
- DataURL与File,Blob,canvas对象之间的互相转换的Javascript
- js深入研究之初始化验证
- javascript压缩图片无刷新上传
- js提交表单kindeditor编辑器textarea为空解决办法
- 轻松学习JavaScript十八:DOM编程学习之DOM简介
- Jsoup的简单使用
- iScroll-js—“smooth scrolling for the web”
- [js开源组件开发]localStorage-cache本地存储的缓存管理
- 给JavaScript初学者的23条最佳实践
- 118 js arale.dialog dialog嵌套时候改变关闭按钮的显示和隐藏状态
- iScroll-js—"smooth scrolling for the web"
- js深入研究之Person类案例
- JavaScript基础(1)prototype方法的理解?
- js深入研究之匿名函数