Object構造函數模式函數
var p = new Object() p.name = 'Tom' p.age = 12 p.setName = function (name){ this.name = name } p.setName('JACK') console.log(p.name,p.age)
對象字面量模式this
問題:若是建立多個對象,有重複代碼prototype
var p = { name:'TOM' age:'12' setName:function(name){ this.name=name } } console.log(p.name,p.age) p.setName('jack') console.log(p.name,p.age) var p2={ name:'BOB' age:'13' setName:function(name){ this.name = name } }
工廠模式code
function creatPerson(name,age){ //返回一個對象的函數==>工廠函數 var obj={ name:name, age:age, setName:function (name){ this.name = name } } return obj } //建立2我的 var p1 = creatPerson('TOM',12) var p2 = creatPerson('BOB',13) //p1,p2是Object類型 function creatStudent(name,price){ var obj = { name:name, price:price } return obj } var s = creatStudent('張三',12000)
自定義構造函數模式對象
問題:每一個對象都有相同的數據,浪費內存內存
//定義類型 function Person(name,age){ this.name = name this.age = age this.setName = function(name){ this.name = name } } var p1 = new Person('TOM',12) p1.setName('JACK') console.log(p1.name,p1.age) function Student(name,price){ this.name = name this.price = price } var s = new Student('BOB',13000) console.log(s instanceof Student) var p2 = new Person('JACK',23) console.log(p1,p2)
構造函數+原型的組合模式原型
適用場景:須要建立多個類型肯定的對象io
function Person(name,age){ this.name = name this.age = age } Person.prototype.setName = function (name){ this.name = name } var p1 = new Person('TOM',23) var p2 = new Person('JACK',24) console.log(p1,p2)