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() 可用。

相关推荐
方见华Richard12 小时前
整数阶时间重参数化:基于自适应豪斯多夫维数的偏微分方程正则化新框架
人工智能·笔记·交互·原型模式·空间计算
方见华Richard2 天前
世毫九《认知几何学修订版:从离散概念网络到认知拓扑动力学》
人工智能·经验分享·交互·原型模式·空间计算
方见华Richard2 天前
自指系统的安全本体论:论内生安全性的哲学基础与形式化路径
人工智能·经验分享·交互·学习方法·原型模式
xianyinsuifeng2 天前
RAG + Code Analysis 的标准路线
数据仓库·自动化·云计算·原型模式·aws
Beginner x_u4 天前
JavaScript 原型、原型链与原型继承的核心机制解析
开发语言·javascript·原型模式·原型原型链
方见华Richard5 天前
递归对抗引擎(RAE)核心极简实现框架
人工智能·交互·学习方法·原型模式·空间计算
方见华Richard5 天前
递归对抗引擎RAE V2.0(多智能体分布式对抗版)
人工智能·经验分享·交互·学习方法·原型模式
方见华Richard6 天前
递归对抗引擎RAE V3.0(碳硅共生版)
人工智能·经验分享·学习方法·原型模式·空间计算
懵萌长颈鹿7 天前
原型模式 (Prototype Pattern)
原型模式
2601_949480067 天前
Flutter for OpenHarmony音乐播放器App实战:定时关闭实现
javascript·flutter·原型模式