JavaScript原型和原型鏈與構(gòu)造函數(shù)和實(shí)例之間的關(guān)系詳解
原型
如圖所示:

1.instanceof檢測構(gòu)造函數(shù)與實(shí)例的關(guān)系:
function Person () {.........}
person = new Person ()
res = person instanceof Person
res // true
2.實(shí)例繼承原型上的定義的屬性:
function Person () {........}
Person.prototype.type = 'object n'
person = new Person ()
res = person.type
res // object n
3.實(shí)例訪問 ===> 原型
實(shí)例通過__proto__訪問到原型 person.proto=== Person.prototype
4.原型訪問 ===> 構(gòu)造函數(shù)
原型通過constructor屬性訪問構(gòu)造函數(shù) Person.prototype.constructor === Person
5.實(shí)例訪問===>構(gòu)造函數(shù)
person.proto.constructor === Person
原型鏈
在讀取一個(gè)實(shí)例的屬性的過程中,如果屬性在該實(shí)例中沒有找到,那么就會(huì)循著 proto 指定的原型上去尋找,如果還找不到,則尋找原型的原型:
1.實(shí)例上尋找
function Person() {}
Person.prototype.type = "object name Person";
person = new Person();
person.type = "我是實(shí)例的自有屬性";
res = Reflect.ownKeys(person); //嘗試獲取到自有屬性
console.log(res);
res = person.type;
console.log(res); //我是實(shí)例的自有屬性(通過原型鏈向上搜索優(yōu)先搜索實(shí)例里的)2.原型上尋找
function Person() {}
Person.prototype.type = "object name Person";
person = new Person();
res = Reflect.ownKeys(person); //嘗試獲取到自有屬性
console.log(res);
res = person.type;
console.log(res); //object name Person3.原型的原型上尋找
function Person() {}
Person.prototype.type = "object name Person";
function Child() {}
Child.prototype = new Person();
p = new Child();
res = [p instanceof Object, p instanceof Person, p instanceof Child];
console.log(res); //[true, true, true] p同時(shí)屬于Object,Person, Child
res = p.type; //層層搜索
console.log(res); //object name Person (原型鏈上搜索)
console.dir(Person);
console.dir(Child);4.原型鏈上搜索
- 原型同樣也可以通過 proto 訪問到原型的原型,比方說這里有個(gè)構(gòu)造函數(shù) Child 然后“繼承”前者的有一個(gè)構(gòu)造函數(shù) Person,然后 new Child 得到實(shí)例 p;
- 當(dāng)訪問 p 中的一個(gè)非自有屬性的時(shí)候,就會(huì)通過 proto 作為橋梁連接起來的一系列原型、原型的原型、原型的原型的原型直到 Object 構(gòu)造函數(shù)為止;
- 原型鏈搜索搜到 null 為止,搜不到那訪問的這個(gè)屬性就停止:
function Person() {}
Person.prototype.type = "object name Person";
function Child() {}
Child.prototype = new Person();
p = new Child();
res = p.__proto__;
console.log(res); //Person {}
res = p.__proto__.__proto__;
console.log(res); //Person {type:'object name Person'}
res = p.__proto__.__proto__.__proto__;
console.log(res); //{.....}
res = p.__proto__.__proto__.__proto__.__proto__;
console.log(res); //null到此這篇關(guān)于JavaScript原型和原型鏈與構(gòu)造函數(shù)和實(shí)例之間的關(guān)系詳解的文章就介紹到這了,更多相關(guān)JavaScript原型與原型鏈內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決layui table表單提示數(shù)據(jù)接口請(qǐng)求異常的問題
今天小編就為大家分享一篇解決layui table表單提示數(shù)據(jù)接口請(qǐng)求異常的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-09-09
Extjs4中tree的拖拽功能(可以兩棵樹之間拖拽) 簡單實(shí)例
這篇文章主要介紹了Extjs4中tree的拖拽功能簡單實(shí)例,有需要的朋友可以參考一下2013-12-12
js點(diǎn)擊頁面其它地方將某個(gè)顯示的DIV隱藏
今天一朋友問我 點(diǎn)擊一按鈕彈出一個(gè)DIV,然后要求點(diǎn)擊頁面其它地方隱藏這個(gè)DIV2012-07-07
詳解JS中定時(shí)器setInterval和setTImeout的this指向問題
在js中setTimeout和setInterval都是用來定時(shí)的一個(gè)功能,下面這篇文章主要給介紹了JS中setInterval和setTImeout的this指向問題,文中通過示例介紹的很詳細(xì),有需要的朋友可以參考借鑒,一起來看看吧。2017-01-01

