原型(Prototype)和原型链

前言

原型(Prototype)和原型链是 JS 中非常重要的一个概念。

原型和原型链机制允许我们在 JavaScript 中通过构造函数的原型,实现方法的共享,从而节省内存并提高代码的效率。

__proto__

在 JS 中,每个对象都有一个 __proto__ 属性,该属性就指向该对象的原型(prototype)。以下是一些输出结果,可以很直观的验证该结论。

const num = 1
console.dir(num.__proto__) // Number
console.log(num.__proto__ === Number.prototype) // true

const str = "1"
console.dir(str.__proto__) // String
console.log(str.__proto__ === String.prototype) // true

const bool = true
console.dir(bool.__proto__) // Boolean
console.log(bool.__proto__ === Boolean.prototype) // true

// ...

const arr = []
console.dir(arr.__proto__) // Array
console.log(arr.__proto__ === Array.prototype) // true

const obj = {}
console.dir(obj.__proto__) // Object
console.log(obj.__proto__ === Object.prototype) // true

需要注意的是,__proto__ 属性是内部属性,在实际开发中,推荐使用 Object.getPrototypeOf()Object.setPrototypeOf() 方法来访问和设置对象的原型。

prototype

在上个代码段中我们使用到了 Number、String 等对象(访问了它们的 prototype 属性),因为他们其实都是 JS 内置函数对象,只有函数对象才拥有 prototype 属性,我们可以通过 prototype.constructor 查看创建它的构造函数。

以普通函数为例(普通函数也可以是构造函数,二者并无本质区别):

function func() {}
// prototype.constructor 记录了创建它的构造函数
console.log(func.prototype.constructor === func) // true
// __proto__ 属性指向它的原型
console.log(func.__proto__ === Function.prototype) // true

显式的声明一个构造函数:

function Car(make, model, year) {
  this.make = make
  this.model = model
  this.year = year
}

Car.prototype.introduce = function () {
  console.log(`I'm the ${this.model}. I'm from ${this.make}. I was made in ${this.year}.`)
}

const beetle = new Car("Volkswagen", "Beetle", 1938)
// prototype.constructor 记录了创建它的构造函数
console.log(Car.prototype.constructor === Car) // true
// __proto__ 属性指向它的原型
console.log(beetle.__proto__ === Car.prototype) // true
// 调用原型上的方法
beetle.introduce() // I'm the Beetle. I'm from Volkswagen. I was made in 1938.

这段代码很明显的说明了:

  • 在 JS 中,每个对象都有一个 __proto__ 属性,指向该对象的原型(prototype)。

  • 函数对象拥有 prototype 属性,prototype.constructor 记录了创建它的构造函数。

原型链

在上面的代码中还表现了原型链的特征。

beetle 本身没有 introduce 方法,却能够调用 introduce 方法,是因为 introduce 方法被添加到了 Car 构造函数的原型上。

Car.prototype.introduce = function () {
  console.log(`I'm the ${this.model}. I'm from ${this.make}. I was made in ${this.year}.`)
}

当调用 beetle.introduce() 时,JavaScript 引擎会首先在 beetle 对象本身上查找 introduce 方法,在 beetle 上找不到该方法,它会继续在 beetle 对象的原型链上查找 Car 构造函数的原型,并最终找到 introduce 方法。

因此,当调用 beetle.introduce() 时,实际上是在 beetle 对象的原型链上找到了 introduce 方法,从而成功调用了该方法。

一张图表示这段代码的原型链:

总结

在 JS 中,每个对象都有一个原型,该原型指向创建该对象的构造函数的 prototype 属性,prototype 本身也是一个对象。

原型链是一个个对象的原型的组合,当访问一个对象的属性或方法时,JS 会在对象自身查找,如果该对象没有这个属性或方法,JavaScript 就会尝试从对象的原型中查找,如果原型中也没有,就会在原型的原型中查找,直接找到或到达原型链的顶端(通常是 Object 的原型),这个查找的过程就组成了原型链。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容