說道原型和原型鏈问慎,首先我們需要了解一下對象這個概念
首先我們用一個簡單常見的方式來創(chuàng)建一個對象
function person(name,age){
this.name = name
this.age = age
this.say = function(){
console.log('hello my name is '+ this.name)
}
}
var objXiaoMing = new person('xiaoming',20)
var objLiLei = new person('lilei',18)
console.log(objXiaoMing.name) //xiaoming
console.log(objXiaoMing.age) //20
objXiaoMing.say() //hello my name is xiaoming
console.log(objLiLei .name) //lilei
console.log(objLiLei .age) //18
objLiLei .say() //hello my name is lilei
這種方式很常見也是經(jīng)常的一種創(chuàng)建對象的方式,通過構(gòu)造函數(shù)實例化一個對象!
people這個函數(shù)我們稱之為構(gòu)造函數(shù),objXiaoMing 我們稱之為這個函數(shù)的實例對象,也稱之為實例
說到這里楞遏,肯定有小伙伴想知道new到底做了什么
- 創(chuàng)建一個新對象;
- 將構(gòu)造函數(shù)的作用域賦給新對象(因此 this 就指向了這個新對象) 首昔;
- 執(zhí)行構(gòu)造函數(shù)中的代碼(為這個新對象添加屬性) 寡喝;
- 返回新對象。
PS:記住這個什么是構(gòu)造函數(shù)勒奇,什么是實例预鬓,下面的內(nèi)容會大量提到
說道創(chuàng)建對象,我們就要說道我們的主題之一撬陵,原型
首先我們使用構(gòu)造函數(shù)創(chuàng)建實例化對象肯定不是為了僅僅創(chuàng)建一個對象珊皿,這樣的話對于代碼的話會比較繁瑣,我們肯定會創(chuàng)建多個對象才會用到上面的方式巨税,但是如果我們使用一個構(gòu)造函數(shù)創(chuàng)建多個對象的話蟋定,那么他們肯定會有相同的屬性和方法,由于每次對象的創(chuàng)建都會開辟空間進行存儲草添,他們相同的屬性就會重復存儲驶兜,這樣的話對性能和內(nèi)存都是一種浪費,我們可以使用原型來操作進行屬性和方法的存儲远寸,具體怎么做呢抄淑?
//每個人都有一個愿望就是世界和平
function person(name,age){
this.name = name
this.age = age
this.say = function(){
console.log('hello my name is '+ this.name)
}
}
person.prototype.wish = functionm(){
console.log('世界和平')
}
var objXiaoMing = new person('xiaoming',20)
var objLiLei = new person('lilei',18)
console.log(objXiaoMing.wish === objLiLei.wish) //true
我們通過打印臺打印的時候就可以發(fā)現(xiàn)結(jié)果是true,因為wish屬于函數(shù),屬于按地址存儲的對象驰后,結(jié)果為ture就可以理解成這兩個對象的方法指向的是同一個內(nèi)存肆资,由此我們可以使用構(gòu)造函數(shù)的原型這個方法來創(chuàng)建相同的屬性和方法
如果認真看到這里,應該能理解什么是原型灶芝,什么是實例化對象郑原,什么是構(gòu)造函數(shù)這三個概念
通過這三個概念我們繼續(xù)引進兩個概念構(gòu)造器和proto
構(gòu)造器 constructor:構(gòu)造函數(shù)實例化對象我們可以簡單的理解成構(gòu)造函數(shù)創(chuàng)建了一個對象,那么這個被創(chuàng)建的對象的構(gòu)造器就是創(chuàng)建他出來的函數(shù)
在上述代碼加入
console.log(objXiaoMing.constructor === person) //true
proto:他屬于實例對象的屬性夜涕,指向的是構(gòu)造函數(shù)的原型
console.log(objXiaoMing.__proto__=== person.prototype) //true
看完這篇文章不要蒙犯犁,我們總結(jié)一下,這篇文章的關(guān)鍵點只有五個概念和兩個指向
- 什么是構(gòu)造函數(shù)
- 什么是實例(實例對象)
- 什么是原型
- 什么是構(gòu)造器
- 什么是proto
指向一
實例對象的constructor指向他的構(gòu)造函數(shù)
實例對象的proto指向構(gòu)造器的原型
最后送個圖方便理解