js原型链prototype解释

复制代码
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__)连接形成的链式结构,用于实现属性和方法的继承。以下是逐步解析:


一、原型链的核心机制

  1. ​每个对象都有一个隐式原型(__proto__)​

    在 JavaScript 中,几乎所有对象(包括函数)都有一个 __proto__ 属性,指向它的构造函数的 prototype 对象。

  2. ​构造函数的 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() 可用。

相关推荐
魔云连洲10 小时前
深入解析:Object.prototype.toString.call() 的工作原理与实战应用
前端·javascript·原型模式
white-persist2 天前
Burp Suite模拟器抓包全攻略
前端·网络·安全·web安全·notepad++·原型模式
青草地溪水旁2 天前
第五章:原型模式 - 克隆大法的大师
c++·设计模式·原型模式
white-persist2 天前
【burp手机真机抓包】Burp Suite 在真机(Android and IOS)抓包手机APP + 微信小程序详细教程
android·前端·ios·智能手机·微信小程序·小程序·原型模式
XiaoLeisj7 天前
【SpringAI】第四弹:深入解析 Rag 检索增强工作流程、最佳实践和调优
阿里云·原型模式·rag·spring ai·灵积大模型
CoderIsArt8 天前
四种对象型创建模式:抽象工厂、 build模式、原型ProtoType与单例模式
单例模式·原型模式
Misnearch9 天前
原型模式了解
原型模式
charlie11451419110 天前
精读《C++20设计模式》——创造型设计模式:原型模式
设计模式·程序设计·原型模式·c++20
Mr_WangAndy12 天前
C++设计模式_创建型模式_原型模式Prototype
c++·设计模式·原型模式
奔跑吧邓邓子12 天前
【C++实战㊷】C++ 原型模式实战:从概念到高效应用
c++·实战·原型模式