prototype 和 __proto__ 的关系,它们一样吗?

三葉Leaves Author

一句话:完全不一样!

  • prototype 是函数的“户口本”,用来登记“子孙后代”应该继承什么。

  • proto 是实例对象的“寻根指针”,用来指向自己的“祖籍”(也就是它爹的户口本)。

一个是“设计图纸”,一个是“指向图纸的箭头”。

通常来说:

  • function 或者说 ES6 里的 class 才有 prototype
  • __proto__ 是实例有的,指向构造函数的 prototype。

有时候有人会用这样的语句比较,发现输出的是 true:

1
2
console.log(heroA.__proto__ === Hero.prototype);
// 输出: true (这才是它们发生关系的地方!)

这是因为它们的值(指向的地址)在一个特定关系下是相同的。

下面这个示例有更详细的说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function Hero(name) {
this.name = name;
}
Hero.prototype.attack = function() { /* ... */ };

let heroA = new Hero('亚瑟');

// 1. prototype 是函数才有的
console.log(Hero.prototype); // 输出: { attack: [Function], constructor: [Function: Hero] }
console.log(heroA.prototype); // 输出: undefined (实例没有 prototype 属性)

// 2. __proto__ 是实例有的,指向构造函数的 prototype
console.log(heroA.__proto__); // 输出: { attack: [Function], constructor: [Function: Hero] }
console.log(Hero.__proto__); // 输出: [Function] (函数也是对象,它的__proto__指向 Function.prototype)

// 3. 关键的连接点!
console.log(heroA.__proto__ === Hero.prototype); // 输出: true (这才是它们发生关系的地方!)
  • 标题: prototype 和 __proto__ 的关系,它们一样吗?
  • 作者: 三葉Leaves
  • 创建于 : 2025-07-22 00:00:00
  • 更新于 : 2025-08-13 16:31:27
  • 链接: https://blog.oksanye.com/a93e463af7b9/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
目录
prototype 和 __proto__ 的关系,它们一样吗?