原型分為隱式原型(prototype)和顯式原型(__proto__)
- 顯式原型:全部函數(shù)且僅限函數(shù)有prototype屬性,只不過(guò)不是構(gòu)造函數(shù),prototype屬性沒(méi)有意義
- 隱式原型:所有引用類(lèi)型都有__proto__屬性,數(shù)組仰税、函數(shù)、對(duì)象...
function A () {
this.name = 'a';
}
A.prototype.print = function () {
console.log('print is called');
}
const B = new A();
B.print();
// 輸出:print is called
實(shí)例B調(diào)用print,會(huì)現(xiàn)先查找當(dāng)前實(shí)例乾闰,沒(méi)有找到print方法;
實(shí)例B和A之間存在一個(gè)隱式鏈接盈滴,實(shí)例B的__proto__屬性會(huì)指向A.prototype涯肩,__proto__就起到了“鏈”的作用,通過(guò)原型鏈實(shí)例B也可以調(diào)用A.prototype上的函數(shù)巢钓。
function A () {
this.name = 'a';
}
A.prototype.name = 'x';
const B = new A();
console.log(B.name);
// 輸出:a
Object.prototype.age = 18;
const C = new A();
console.log(C.age);
// 輸出:18
console.log(C.gender);
// 輸出:undefined
原型鏈遵循就近原則病苗,當(dāng)前實(shí)例有name屬性時(shí),會(huì)使用當(dāng)前實(shí)例的屬性症汹,當(dāng)當(dāng)前實(shí)例不存在age屬性時(shí)硫朦,會(huì)根據(jù)__proto__向上查找,直到找到Object.prototype背镇,如果仍然不存在則返回undefined