js类和对象
2016-01-20 10:30
543 查看
<pre name="code" class="javascript">【门户大开式对象】 var Book=function(isbn,title,author){ this.setIsbn(isbn,title,author); 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'; } }; 【封装】 var Book=function(newIsbn,newTitle,newAuthor){ //私有字段 var isbn,title,author; //私有方法 function checkIsbm(isbn){ ... } //特权方法 通过对象可访问 this.getIsbn=function(){ return isbn; }; this.setIsbn=function(newIsbn){ if(!checkIsbn(isbn)) throw new Error('Book: Invalid ISBN.'); isbn=isbn; }; 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); } //公有 Book.prototype={ display:function(){ ... } }; 【继承】 function Person(name){ this.name=name; } Person.prototype.getName=function(){ return this.name; } //用来实现继承 function extend(subClass,superClass){ var F=function(){}; F.prototype=superClass.prototype; subClass.prototype=new F(); subClass.prototype.constructor=subClass; subClass.superClass=superClass.prototype; if(superClass.prototype.constructor==Object.prototype.constructor){ superClass.prototype.constructor=superClass; } } function Author(name,books){ Author.superClass.constructor.call(this,name); this.books=books; } extend(Author,Person); Author.prototype.getBooks=function(){ return this.books; }
相关文章推荐
- JS自执行匿名函数
- js class expression
- 我理解的javascript万物皆对象
- js instanceof
- JS在遍历二维数组的时候会出现无限遍历,卡死的问题
- 好玩的js特效
- JavaScript清除Cookie完全攻略--被domain和path折磨
- JavaScript 的 Prototype 原型链详解(转)
- 动态加载JavaScript
- js typeof
- javascript数据类型
- 用JS获取url参数的方法
- js 获取范围内的随机数
- 搭建AngualarJS开发环境
- JSON遇到懒加载错误解决方案
- JavaScript高级程序设计学习笔记一在HTML中使用JS
- Javascript模板引擎mustache.js详解
- script中js导入外部js文件
- js实现图片无缝滚动特效
- cookie、session、sessionid 与jsessionid