先看代碼
//利用閉包實(shí)現(xiàn)
var Book = (function(){ //按照編程習(xí)慣一般講代表類的變量名首字母大寫
//靜態(tài)私有變量
var bookNum = 0;
//靜態(tài)私有方法
function checkBook(name){};
//創(chuàng)建類
function _book(newID, newName, newPrice){
//私有變量
var name, price;
//私有方法
function checkID(id){}
//特權(quán)方法
this.getName = function(){};
this.getPrice = function(){};
this.setName = function(){};
this.setPrice = function(){};
//公有屬性
this.ID = newID;
//公有方法
this.copy = function(){};
bookNum++
if(bookNum > 100)
throw new Error('我們僅出版100本書.');
//構(gòu)造器
this.setName(name);
this.setPrice(price);
}
//構(gòu)建原型
_book.prototype = {
//靜態(tài)公有屬性
isJSBook : false;
//靜態(tài)公有方法
display : function(){};
};
//返回類
return _book;
})()
基本思想
在一個立即執(zhí)行函數(shù)中構(gòu)建一個閉包(通過構(gòu)造函數(shù)和構(gòu)建原型)來創(chuàng)建一個類,然后通過return返回類并賦值給一個全局變量;