js设计模式=封装

js封装案例【1】

<script>var Book = function(num){ var num;//类私有变量 var name;//类私有变量 function check(){};//类私有方法 this.checkName = function(){}//特权方法}Book.prototype.checkNum=10;//公共属性Book.prototype.display=function(){//公共方法 console.log("this is display");}Book.isChinese=true;//类似静态功能属性Book.checkInfo=function(){}//类似静态功能方法var b1 = new Book();b1.display();</script>

 js使用闭包完成封装【2】

<script>var Book =(function(){ //静态私有变量 var bookNum=0; //静态私有方法 function checkBook(name){ console.log(name); } //使用了闭包 return function(newId,newName,newPrice){ //私有变量 var name,price; //私有方法 function checkId(){ console.log(bookNum); } //特权方法=和外面交互 this.getName = function(){ console.log(this.name); } this.getPrice= function(){ console.log(this.price); } this.setPrice= function(newPrice){ this.price = newPrice; } this.setName = function(newName){ this.name = newName; } this.copy = function(){} this.setName(newName); this.setPrice(newPrice); bookNum++; checkId(); checkBook(newName); }})();//静态属性和方法Book.prototype={ isjsBook:false, display:function(){}};var book = new Book(1,jsBook,30);book.getName();book.getPrice();</script>

  js使用闭包完成封装【3】

<script> var Book = (function(){ //静态私有变量 var bookNum=0; //静态私有方法 function checkBook(name){} function book (newId,newName,newPrice){ //私有变量 var book,price; //私有方法 function checkId(){} //特权方法&属性 this.getName = function(){} this.getPrice = function(){} this.setName = function(){} this.setPrice = function(){} this.copy=function(){} //构造方法和属性 this.id = newId; this.setName(newName); this.setPrice(newPrice); } //构造原型 book.prototype={ isJSBook:true, display:function(){console.log()} }; return book; })(); var book = new Book(1,jsbook,20); book.display(); //备注这样看来是一个完整的整体</script>

 

相关文章