function Person(){}
var person=new Person()
console.log('======啊啊',Person instanceof Function);//true
console.log('======',Person.__proto__==Function.prototype);//true
console.log('======',Person.prototype.__proto__ === Object.prototype);//true
console.log('======',Function.prototype.__proto__==Object.prototype);//true
var arr=[]
console.log('======',arr.__proto__==Array.prototype);//true
console.log('======',Array.prototype.__proto__==Object.prototype);//true
function Animal() {}
Animal.prototype.eat = function() { console.log("Eating...") };function Dog() {}
Dog.prototype = new Animal(); // Dog 繼承 Animal
Dog.prototype.bark = function() { console.log("Bark!") };const myDog = new Dog();
console.log('======',myDog.__proto__.__proto__=== Animal.prototype);//true
上述代碼都是true?
理解 JavaScript 中的??原型鏈(Prototype Chain)??是掌握其面向對象編程的核心。原型鏈的本質是通過對象的隱式原型([[Prototype]]
,即?__proto__
)連接形成的鏈式結構,用于實現屬性和方法的繼承。以下是逐步解析:
一、原型鏈的核心機制
-
??每個對象都有一個隱式原型(
__proto__
)??
在 JavaScript 中,幾乎所有對象(包括函數)都有一個?__proto__
?屬性,指向它的構造函數的?prototype
?對象。 -
??構造函數的?
prototype
?屬性??
每個函數在創建時會自動生成一個?prototype
?屬性,它是一個對象,其中默認包含?constructor
?屬性指向函數自身。例如:function Person() {} console.log(Person.prototype.constructor === Person); // true
3.??實例的原型鏈形成??
當通過?new
?創建實例時,實例的?__proto__
?會指向構造函數的?prototype
?對象:
const person = new Person();
console.log(person.__proto__ === Person.prototype); // true
???4.鏈式繼承??
如果構造函數的?prototype
?本身也有?__proto__
,則會繼續向上查找,直到?Object.prototype
,最終指向?null
:
console.log(Person.prototype.__proto__ === Object.prototype); // true
console.log(Object.prototype.__proto__); // null
原型鏈的層級關系
function Animal() {}
Animal.prototype.eat = function() { console.log("Eating...") };function Dog() {}
Dog.prototype = new Animal(); // Dog 繼承 Animal
Dog.prototype.bark = function() { console.log("Bark!") };const myDog = new Dog();// 原型鏈層級:
// myDog → Dog.prototype → Animal.prototype → Object.prototype → null
myDog
?可以訪問?bark
(來自?Dog.prototype
)和?eat
(來自?Animal.prototype
)。- 所有對象最終繼承自?
Object.prototype
,因此?myDog.toString()
?可用。
?
?