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

相关推荐
想吃火锅100514 天前
【前端手撕】instanceof
前端·javascript·原型模式
UXbot14 天前
帮助企业低门槛开展AI应用开发的平台推荐
前端·低代码·ui·交互·产品经理·原型模式·web app
UXbot15 天前
如何选择适合公司项目的UI设计工具?企业选型指南
前端·低代码·ui·团队开发·原型模式·设计规范·web app
UXbot15 天前
原型设计工具如何帮助新人快速进入产品行业?
前端·低代码·ui·交互·团队开发·原型模式·web app
sunny.day19 天前
js原型与原型链
开发语言·javascript·原型模式·js原型链
UXbot20 天前
AI网页开发工具能替代工具吗?5大平台对比
前端·人工智能·低代码·ui·原型模式·web app
weixin_3077791320 天前
从“大海捞针”到“主动推理”:AI如何重塑云原生故障诊断的根因链
开发语言·人工智能·算法·自动化·原型模式
swordbob20 天前
prototype 注入到 singleton 里,prototype是否还是线程安全的
安全·spring·单例模式·原型模式
isNotNullX21 天前
企业数据中台建设,ETL工具选错了会踩哪些坑?
数据仓库·etl·原型模式
半个烧饼不加肉21 天前
JS 底层探究-- 普通函数和构造函数
开发语言·javascript·原型模式