门户大开式对象
var Book=function(isbn,title,author){ if (isbn==undefined) throw new Error("不合法"); this.isbn=isbn; this.title=title||'无标题'; this.author||'无作者'; } Book.prototype.display=function(){ ... };
强化版本
var Book=function(isbn,title,author){ if (!this.checkIsbn(isbn)) throw new Error("ISBN无效"); this.isbn=isbn; this.title=title||'无标题'; this.author||'无作者'; } Book.prototype={ checkIsbn:function(isbn){ if (isbn==undefined||typeof isbn!='string') { return false; } isbn=isbn.replace(/-/,''); if (isbn.length!=10 &&isbn.length!=13) { return false; } var sum=0; if (isbn.length===10) { if(!isbn.match(/^d{9}/)){ return false; } for(var i=0;i<9;i++){ sum +=isbn.charAt(i)*(10-i); } var checksum=sum%11; if(checksum===10)checksum='X'; if (isbn.charAt(9)!=checksum) { return false; } } else{ if(!isbn.match(/^d{12}/)){ return false; } for(var i=0;i<12;i++){ sum+=isbn.charAt(i)*((i%2===0)?1:3); } var checksum=sum%10; if(isbn.charAt(12)!=checksum){ return false; } } return true; }, display:function(){ ... } };
更进一步
var Publication=new Interface('Publication',['getIsbn','setIsbn','getTitle','setTitle','getAuthor','setAuthor','display']); var Book=function(isbn,title,author){ this.setIsbn(isbn); 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("ISBN不合法"); this.isbn=isbn; }, getTitle:function(){ return this.title; }, setTitle:function(title){ this.title=title||"无标题"; }, getAuthor:function(){ return this.author; }, setAuthor:function(author){ this.author=author||"无作者"; }, display:function(){ ... } };
为了防止其他程序员的无意使用,可以在私有方法和属性前加_表明是私有
用闭包实现私用成员
var Book=function(newIsbn,newTitle,newAuthor){ var isbn,title,author; function checkIsbn(isbn){ ... } this.getIsbn=function(){ return isbn; }; this.setIsbn=function(newIsbn){ if(!checkIsbn(newIsbn)) throw new Error("ISBN不合法"); isbn=newIsbn; }; this.getTitle=function(){ return title; }; this.setTitle=function(newTitle){ title=newTitle||'无标题'; }; this.getAuthor=function(){ return author; }; this.setAuthor=function(newAuthor){ author=newAuthor||'无作者'; }; this.setIsbn(newIsbn); this.setTitle(newTitle); this.setAuthor(newAuthor); }; Book.prototype={ display:function(){ ... } };