一、經過new object方法或者字面量的方式創造對象函數
var obj = new Object() var obj1 = {}
缺點:創造多個key同,value不一樣的對象的時候會產生大量的重複代碼(重複的書寫key=value)this
二、工廠模式spa
function CreateObj(...arg){ let obj = new Object() let attrs = ['a','b','c'] attrs.forEach((attr,index)=> { obj[attr] = arg[index] || null }); return obj }
缺點:沒法解決對象的識別問題(x.constructor === Object,x爲工廠模式建立出來的對象)prototype
三、構造函數模式(沒法複用屬性)與原型模式 (屬性共享)code
四、組合構造函數+原型模式對象
function People(name){ this.name = name } People.prototype.say = function(){ return 'hello' }
五、動態原型模式(更好的封裝,把全部屬性都放在一個方法內部)blog
function People(name,fn){ if(fn&& typeof fn !== 'function')throw 'fn must be a function' this.name = name if(!fn){ People.prototype.say = function(){ return 'hello' } }else{ this.say = fn } }
六、Object.create(_pro_)原型
七、寄生構造函數(和工廠模式同樣,只是調用方式上存在差別,就是在其餘構造函數上的一個擴展,我的以爲沒啥用)io
function MyArray(){ let ary = new Array() ary.test = function(){ alert(ary[0]||'沒有值') } return ary } let myarry = new MyArray() myarry.test()
八、穩妥構造函數(內部不能使用this,私有屬性不能定義在對象上,只能定義在方法內部,調用時不能用new)function
function Student(name){ let obj = new Object() let name = name //這裏不能寫爲obj.name = name obj.sayName = function(){ return name } return obj } let stu1 = Student('zale')