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

相关推荐
我登哥MVP11 天前
走进 Gang of Four 设计模式:访问者模式
java·设计模式·访问者模式·原型模式
学究天人12 天前
数学公理体系大全:第五章 序数与基数理论:超限算术与集合的大小
人工智能·线性代数·算法·机器学习·数学建模·原型模式
学究天人12 天前
数学公理体系大全:第六章 选择公理的等价形式及证明
人工智能·线性代数·算法·机器学习·数学建模·概率论·原型模式
学究天人13 天前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(补充卷9)
人工智能·线性代数·算法·数学建模·动态规划·原型模式·抽象代数
geovindu14 天前
CSharp: Prototype Pattern
开发语言·后端·设计模式·.net·原型模式·创建型模式
Seven凹凸Man14 天前
WorkBuddy之产品经理原型设计及PRD实战
ai·原型模式
ttod_qzstudio15 天前
【软考设计模式】原型模式:“克隆“对象与深拷贝、浅拷贝精讲
设计模式·原型模式
希冀12319 天前
【JavaScript】Javascript—JS进阶—Day03
开发语言·javascript·原型模式
想吃火锅10051 个月前
【前端手撕】instanceof
前端·javascript·原型模式
UXbot1 个月前
帮助企业低门槛开展AI应用开发的平台推荐
前端·低代码·ui·交互·产品经理·原型模式·web app