創(chuàng)建對(duì)象
工廠模式
解決了創(chuàng)建相似對(duì)象的問題,但沒有解決對(duì)象識(shí)別的問題
function createPerson(name, age, job) {
var o = new Object()
o.name = name;
o.age = age;
o.sayName = function() {
alert(this.name)
}
return o;
}
var person1 = createPerson('Lime', 26, 'Developer')
構(gòu)造函數(shù)模式
解決了對(duì)象識(shí)別的問題炫惩,構(gòu)造函數(shù)產(chǎn)生的實(shí)例擁有 Constructor 屬性僻弹,指向構(gòu)造函數(shù)。
存在問題他嚷,沒必要在每一個(gè)實(shí)例中創(chuàng)建完成同樣任務(wù)的不同F(xiàn)unction
function Person(name, age, job) {
this.name = name;
this.age = job;
this.sayName = function() {
alert(this.name)
}
}
var person1 = new Person('Lime', 26, 'Developer')
// 補(bǔ)充:在另一個(gè)作用域中調(diào)用構(gòu)造函數(shù)
var o = new Object();
Person.call(o, 'Lime', 26, 'Developer')
組合構(gòu)造函數(shù)
構(gòu)造函數(shù)模式用于定義實(shí)例屬性蹋绽,而原型模式用于定義方法和共享屬性芭毙。
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Shelly", "Court"]
}
Person.prototype = {
constructor: Person,
sayName: function(){
alert(this.name)
}
}
var person1 = new Person('Lime', 26, 'Developer')
動(dòng)態(tài)原型模式
將組合構(gòu)造函數(shù)中構(gòu)造函數(shù)和原型封裝在一整塊
function Person(name, age, job){
// 屬性
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Shelly", "Court"];
//方法
if(typeof this.sayName != "function") {
Person.prototype.sayName = function() {
alert(this.name)
}
}
}
繼承
原型鏈
讓一個(gè)引用類型繼承另一個(gè)引用類型的屬性和方法
function SuperType(){
this.property = true;
}
SuperType.prototype.getSuperValue = function(){
return this.property;
}
function SubType(){
this.subproperty = false;
}
// 繼承了SuperType
SubType.prototype = new SuperType();
組合繼承
使用原型鏈實(shí)現(xiàn)對(duì)原型屬性和方法的繼承,而通過借用構(gòu)造函數(shù)實(shí)現(xiàn)對(duì)實(shí)例屬性的繼承
不足在于調(diào)用了兩次超類型
function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"]
}
SuperType.prototype.sayName = function(){
alert(this.name)
}
function SubType(name, age){
//繼承屬性
SuperType.call(this, name)
this.age = age
}
//繼承方法
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
var instance = new SubType();
寄生組合式繼承
不必為了指定子類型的原型而調(diào)用超類型的方法卸耘,所需要的只是超類型原型的一個(gè)副本
function inherit(subType, superType){
var prototype = Object.create(superType.protptype) //創(chuàng)建對(duì)象
prototype.constructor = subType //增強(qiáng)對(duì)象
subType.prototype = prototype //指定對(duì)象
}
function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"]
}
SuperType.prototype.sayName = function(){
alert(this.name)
}
function SubType(name, age){
//繼承屬性
SuperType.call(this, name)
this.age = age
}
inherit(SubType, Supertype)
使用 new 操作符 時(shí)經(jīng)歷的四個(gè)階段
Person(name) {
this.name = name
}
var person1 = new Person()
- 創(chuàng)建新的對(duì)象
- 將構(gòu)造函數(shù)的作用域賦給新對(duì)象退敦,即this指代新對(duì)象
- 執(zhí)行構(gòu)造函數(shù)中的代碼
- 返回新的對(duì)象