JavaScript封装

2017-11-28  本文已影响0人  梦里Bug知多少

类的创建

//类
var Book = function(id,name){
   //私有属性
   var bookid = id;
   //私有方法
   function checkId(){
      if (id == 1){
         return true;
      }else {
         return false;
      }
   }
   //特权方法  
   this.setName =  function (name) {    console.log("this特权方法:"+name);}
  //对象共有属性
  this.id = id;
  //对象公用方法
  this.copy =  function(){
    console.log("this特权方法:"+name);
  }
  //构造器
  this.setName(name);
}
//类公用方法和公用属性
Book.protptype = {
   isJSBook = true;
   display:function(){
   }
}
//类静态公用方法和公用属性
Book.isBook = true;
Book.display = function(){
console.log("this is 类静态公用方法")
}

this上定义的属性和方法都可以new一个实例来使用,eg: var a = new Book()。
而类通过点生产的方法是对象的静态共有属性和静态共有方法,是无法使用new出的实例访问的。但是类通过prototype创建的公用方法和公用属性是可以通过this访问到的。

var book = new Book(1,"niubi");
console.log(book.bookid);//私有属性无法访问
console.log(book.id);//返回1
book.setName();//返回this is 类静态公用方法
console.log(book.isBook);//对象访问:undefined
console.log(Book.isBook);//类访问是没问题的:true
Book.display();//类访问是没问题的:this is 类静态公用方法

闭包

闭包是有权访问另外一个函数作用域变量的函数,也是一个函数内部的函数。
eg:

var Book =(function(){
  var bookNum = 0;//私有变量
  function checkBook(name) {}//私有方法
  function _book(newId,newName,newPrice) {
      var name,price;  //闭包私有变量
      name = newName;
      this.getName = function () {
          return name;
       }
      this.getNum = function () {
          return bookNum; 
      } 
   }
  return _book;//返回类
})();

//测试
<script>
var book = new Book(1,"niubi","123");
console.log(book.getName());//niubi
console.log(book.getNum()); //0 
</script>
上一篇下一篇

猜你喜欢

热点阅读