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

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;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: