更多文章查看本專欄
閉包能夠理解爲'類生成器'
閉包代碼:設計模式
var Book = (function(){ var bookNum = 0; function checkBook(name){ } return function(newId,newName,newPrice){ var name,price; this.id = newId; bookNum++; if(bookNum > 100){ throw new Error('最多隻出版100本書'); } function checkID(id){} this.getName = function(){ console.log(name); return name; }; this.getPrice = function(){ console.log(price); return price; }; this.setName = function (mName) { name = mName; }; this.setPrice = function (mPrice) { price = mPrice; }; this.copy = function () {}; // 構造器 this.setName(newName); this.setPrice(newPrice); } })(); Book.prototype = { isJSBook: false, display: function () { } }
使用:安全
var myBook = new Book('id','name','price');
使用方法與普通的是一致的。
可是若是不加new關鍵詞的話閉包
var myBook = Book('id','name','price');
當不使用new關鍵詞的時候只會將Book執行一遍而且this指針爲window
而且全部的值都在this
能夠使用將return的function寫爲一個私有的類,而且將外部的prototype寫在裏面,讓閉包看起來更加的舒服,更像是一個總體。prototype
在使用類的時候可能會忘記使用new關鍵詞。這個時候調用就像上面說的那種。執行一遍代碼,而且其中的this指向window。設計
能夠使用安全模式避免忘記使用new的狀況。指針
列子:code
var Book = function (title,time,type) { if(this instanceof Book){ this.title = title; this.time = time; this.type = type; }else{ return new Book(title,time,type); } }
本質能夠看出就是加了一層判斷。對象
當原型鏈上的值爲引用的時候:繼承
var test = function () { } test.prototype.nums = [1,2,3,4]; ins1 = new test(); ins2 = new test(); console.log(ins2.nums); ins1.nums.push(5); console.log(ins2.nums);
這裏就能夠看出來若是原型鏈上的值爲引用類型的時候會出現問題。
多繼承的實現就是將父類們的全部屬性進行拷貝到一個到當前類上。
當遇到引用類型的時候應當深拷貝,可是此處咱們只討論淺拷貝的問題。
如下代碼爲多繼承:
var mix = function () { var len = arguments.length; var target = arguments[1]; var arg; for(var i = 1;i < len;i++){ arg = arguments[i]; for(var property in arg){ target[property] = arg[property]; } } return arg; }
多態是對arguments裏面的值得個數進行統計,根據不一樣的狀況給予不一樣的迴應。
簡單例子
var add = function () { var len = arguments.length; switch (len) { case 0: return 10; case 1: return 10 + arguments[0]; case 2: return arguments[0] + arguments[1]; } }