闭包
闭包的主要作用就是构建一个单独的作用域,里面的一些变量不会污染全局,又可以满足一些必要操作
比如bookNum,写在外部会污染全局,写在_book里函数中, 静态使用一次又会被销毁, 实例又无法从外部访问
const Book = (function () { // 私有变量 let bookNum = 0 // 私有方法 function checkBook(name) {} // 创建类 function _book(newId, newName, newPrice) { // 私有变量 let name, price // 私有方法 function checkID(id) {} // 特权方法 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") } // 构造器 this.setName(name) this.setPrice(price) } // 构建原型 _book.prototype = { // 静态公有属性 isJSBook: true, // 静态公有方法 display: function () {} } return _book })() const book = new Book(1, "JS", 100) console.log(book)