JavaScript:原型对象和原型链

原型类比

JavaScript中的原型,相当C++、JAVA的 父类

函数原型对象

每一个函数都有一个 prototype 属性(显式原型),指向原型对象。

普通函数的 prototype 属性,作用不大

案例

function test(){

}
console.log(test.prototype)

显示如下:中

是一个只有属性 constructor 的对象,属性 constructor 指向函数自身

console.log(test.prototype.constructor === test)

结果如下:

true

构造函数 的 原型对象

把函数作为构造函数 (理论上任何函数都可以作为构造函数),prototype 属性(显式原型),指向 构造函数 的 原型对象(即:父类对象)

使用 new 创建对象时,这个对象就有 __proto__ 属性(隐式原型),来指向了构造函数的原型对象(即:也是父类对象)

案例

function Student(name,age){
    this.name = name
    this.age = age
}
const lilei = new Student("李雷",20)
console.log(lilei)
console.log("对象.__proto__",lilei.__proto__)
console.log("函数.prototype",Student.prototype)
console.log("指向构造函数原型对象:",lilei.__proto__ === Student.prototype)

执行结果如下:

结论: 对象的 __proto__ 属性 指向了构造函数的原型对象,与构造函数无关

创建多个对象时

function Student(name,age){
    this.name = name
    this.age = age
}
const lilei = new Student("李雷",20)
const hmm = new Student("韩梅梅",21)

console.log("指向构造函数原型对象:",lilei.__proto__ === Student.prototype)
console.log("指向构造函数原型对象:",hmm.__proto__ === Student.prototype)
console.log("指向构造函数原型对象:",lilei.__proto__ === hmm.__proto__)

执行结果:

指向构造函数原型对象: true
指向构造函数原型对象: true
指向构造函数原型对象: true

结论: 同一个构造函数,创建多个对象,对象的 __proto__ 属性相同,都指向了构造函数的原型对象,与构造函数无关

构造函数原型的作用 - 继承

构造函数创建对象后,当访问其中的一个属性或方法的时候,如果这个对象中 没有 这个属性或方法,那么将会访问这个对象的 __proto__ 属性所指向的原型对象,并在原型对象中查找属性或方法,如果不能找到,那就会继续通过那个对象 的 __proto__ 属性指向的原型对象继续查找。

Object 对象的原型没有原型,即:Object 的__proto__属性是 null,如果在 Object 中依然没有中找到属性,则返回 undefined

案例

function Student(name,age){
    this.name = name
    this.age = age
}
const lilei = new Student("李雷",20)

console.log(lilei.toString())
console.log(lilei)

执行结果如下:

结论: 虽然 lilei 对象没有 toString() 方法,但其原型有 toString() 方法,所以仍然可以调用

prototype(对象属性)的所有属性和方法,都会被构造函数的实例继承。

原型链

构造函数创建对象后,这个对象的 __proto__ 属性所指向的原型对象,该原型对象 的 __proto__ 属性指向的原型对象,一直指向 Object 对象,Object 的原型没有原型,即:Object 的__proto__属性是 null

参考:
https://www.jianshu.com/p/72156bc03ac1
https://blog.csdn.net/u012468376/article/details/53121081


原文出处:/show_1IX3jND76LA4.html