1.構(gòu)造函數(shù)
一開始this指向一個(gè)空對象 最后返回這個(gè)對象
構(gòu)造函數(shù)和一般函數(shù)的區(qū)別:
1.使用方式
通過new執(zhí)行后構(gòu)造函數(shù)就是一個(gè)類了
2.在函數(shù)代碼執(zhí)行的時(shí)候
相同點(diǎn):形成一個(gè)私有作用域(形參賦值->預(yù)解釋->順序執(zhí)行)
不同點(diǎn):不需要手動(dòng)創(chuàng)建對象 最后不需要手動(dòng)返回這個(gè)對象
image.png
image.png
2、原型規(guī)則和示例
image.png
image.png
1)每一個(gè)函數(shù)數(shù)據(jù)類型(普通函數(shù)馏锡、類(構(gòu)造函數(shù)))都有一個(gè)屬性:prototype(顯式原型)并且該屬性是一個(gè)對象類型
2)并且在prototype上瀏覽器天生給他加了一個(gè)constructor(構(gòu)造器)屬性值是當(dāng)前函數(shù)(類)本身
3)每一個(gè)對象數(shù)據(jù)類型(普通對象雷蹂、實(shí)例、prototype杯道,null除外)也天生自帶一個(gè)屬性:proto屬性(隱式原型)匪煌,屬性值是當(dāng)前實(shí)例所屬類的原型(prototype )
image.png
image.png
4)當(dāng)通過對象名.屬性值獲取對象的屬性的時(shí)候,首先會在對象的私有屬性上查找如果有就返回沒有的話就去找proto即所屬類的原型(上面都是這個(gè)類的公共屬性和方法)党巾,如果沒有再向上找一直找到Object為止如果還沒有返回undefined
image.png
3 this和原型擴(kuò)展
1)類中的this this.xxx=xxx this指向當(dāng)前類的實(shí)例
2)方法中的this調(diào)用該方法的時(shí)候方法名點(diǎn)前面是誰 this就是誰
image.png
4原型鏈繼承
//原型鏈繼承方式
//1.原型繼承【父所有為子公有】 最常見
function A(){
this.x=100
}
A.prototype.getX=function(){
console.log(this.x)
}
function B1(){
this.y=200
}
B1.prototype=new A
B1.prototype.constructor=B1 //嚴(yán)謹(jǐn)?shù)脑捈由线@句
let b1=new B1
console.log(b1.x)
//2.call繼承【父私有為子私有】
function B2(){
A.call(this)
}
let b2=new B2
console.log(b2.x)
//3.冒充對象繼承【父所有為子私有】
function B3(){
var temp =new A
for(let k in temp){ //復(fù)制父的私有和自定義公有
this[k] = temp[k]
}
temp = null //優(yōu)化
}
let b3=new B3
console.log(b3.x)
//4.混合模式【父私有變子私有萎庭,父所有為子公有】
function B4(){
A.call(this)//父私有變子私有
}
B4.prototype=new A
let b4=new B4
console.log(b4.x)
//5.寄生組合模式【父私有為子私有 父公有為子公有】
function B5(){
A.call(this)//父私有變子私有
}
B5.prototype=create(A.prototype)
let b5=new B5
console.log(b5.x)
b5.getX()
//ie 678不支持Object.create()
function create(obj){
function F(){}
F.prototype=obj;
return new F;
}
image.png
image.png